Dowemo
0 0 0 0

It has to say that microsoft 's technology iteration is still fast, and microsoft 's ships go along with her. The asp core 2.0 learning note ( one ):NET core2 sdk.

Introduction:

The entity framework ( ef ) is the ADO.NET/R mapping solution developed by microsoft based on. The ef core is the next ve ion of the entity framework. Compared to the old ve ion of 4-6. 1 (. ), it's a bit more lightweight, but it has a lot of problems in the configuration process.

creation and fluent api relationship configuration

A relatio & hip:

The most common in the project is a relationship, as an example of language and language.

Language class ( language ) class

 1publicpartialclass Language : BaseEntity<int> 2 { 3private ICollection<LocaleStringResource> _localeStringResources; 4 5///<summary> 6/// Gets or sets the name 7///</summary> 8 9publicstring Name { get; set; }1011///<summary>12/// Gets or sets the language culture13///</summary>1415publicstring LanguageCulture { get; set; }1617///<summary>18/// Gets or sets the unique SEO code19///</summary>2021publicstring UniqueSeoCode { get; set; }2223///<summary>24/// Gets or sets the flag image file name25///</summary>2627publicstring FlagImageFileName { get; set; }2829///<summary>30/// Gets or sets a value indicating whether the language supports"Right-to-left"31///</summary>3233publicbool Rtl { get; set; }343536///<summary>37/// Gets or sets a value indicating whether the language is published38///</summary>3940publicbool Published { get; set; }4142///<summary>43/// Gets or sets the display order44///</summary>4546publicint DisplayOrder { get; set; }4748publicbool IsDefault { get; set; }4950///<summary>51/// Gets or sets locale string resources52///</summary>53publicvirtual ICollection<LocaleStringResource> LocaleStringResources54 {55get { return _localeStringResources?? (_localeStringResources = new HashSet<LocaleStringResource>()); }56protectedset { _localeStringResources = value; }57 }
View Code

Language resources ( localestringresource ):

 1publicpartialclass LocaleStringResource : BaseEntity<int> 2 { 3///<summary> 4/// Gets or sets the language identifier 5///</summary> 6publicint LanguageId { get; set; } 7 8///<summary> 9/// Gets or sets the resource name10///</summary>11publicstring ResourceName { get; set; }1213///<summary>14/// Gets or sets the resource value15///</summary>16publicstring ResourceValue { get; set; }1718///<summary>19/// Gets or sets a value indicating whether this resource was installed by a plugin20///</summary>21publicbool? IsFromPlugin { get; set; }2223///<summary>24/// Gets or sets a value indicating whether this resource was modified by the user25///</summary>26publicbool? IsTouched { get; set; }2728///<summary>29/// Gets or sets the language30///</summary>31publicvirtual Language Language { get; set; }3233 }
View Code

The language and resource primary key relationships are configured as follows

 1publicpartialclass LanguageMapper : IEntityTypeConfiguration<Language> 2 { 3publicvoid Configure(EntityTypeBuilder<Language> builder) 4 { 5 builder.ToTable("Language"); 6 builder.HasKey(r => r.Id); 7 builder.HasIndex(r => r.LanguageCulture); 8 builder.HasIndex(r => r.Name); 9 builder.HasIndex(r => r.UniqueSeoCode);10 }11 }
View Code
publicpartialclass LocaleStringResourceMapper : IEntityTypeConfiguration<LocaleStringResource> {
 publicvoid Configure(EntityTypeBuilder<LocaleStringResource> builder)
 {
 builder.ToTable("LocaleStringResource");
 builder.HasKey(r => r.Id);
 builder.HasIndex(r => r.LanguageId);
 builder.HasIndex(r => r.ResourceName);
 builder.HasOne(r => r.Language).WithMany(b => b.LocaleStringResources)
. HasForeignKey(fk => fk.LanguageId);
 }
 }

2, relatio & hip:

 1publicclass TechCategory:BaseEntity<int> 2 { 3///<summary> 4/// 名称 5///</summary> 6publicstring Name { get; set; } 7///<summary> 8/// 分类描述 9///</summary>10publicstring Descript { get; set; }11///<summary>12/// meta标题13///</summary>14publicstring MetaTitle { get; set; }15///<summary>16/// meta描述17///</summary>18publicstring MetaDescript { get; set; }19///<summary>20/// 缩略图21///</summary>22publicstring Thumb { get; set; }23///<summary>24/// 图片25///</summary>26publicstring Image { get; set; }27///<summary>28/// 排序29///</summary>30publicint Sort { get; set; }31///<summary>32/// 父级分类33///</summary>34publicint? ParentId { get; set; }3536///<summary>37/// 父级分类38///</summary>3940publicvirtual TechCategory Parent { get; set; }41publicvirtual ICollection<Technology> Technologys { get; set; }42///<summary>43/// 子级44///</summary>45publicvirtual ICollection<TechCategory> Childs { get; set; }46///<summary>47/// 关键词48///</summary>49publicstring Slug { get; set; }50///<summary>51/// 创建时间52///</summary>53publiclong CreatedOn { get; set; }54 }
View Code
 1publicclass TechCategoryMapper : IEntityTypeConfiguration<TechCategory> 2 { 3publicvoid Configure(EntityTypeBuilder<TechCategory> builder) 4 { 5 builder.ToTable("TechCategory"); 6 builder.HasKey(r => r.Id); 7 builder.HasMany(r => r.Childs).WithOne(x => x.Parent) 8. HasForeignKey(fk => fk.ParentId); 9 builder.HasIndex(r => r.Name);10 }11 }
View Code

Second, database context:

According to the related entity classes created earlier and related mapper types, we can reproduce the OnModelCreating method of dbcontext, reflecting the related mapping

 1publicclass DefaultContext : DbContext 2 { 3public DefaultContext(DbContextOptions<DefaultContext> opt) 4 :base(opt) 5 { 6 AutoCommitEnabled = true; 7 } 8protectedoverridevoid OnModelCreating(ModelBuilder builder) 9 {10base.OnModelCreating(builder);11var mappingInterface = typeof(IEntityTypeConfiguration<>);12// Types that do entity mapping13var mappingTypes = GetType().GetTypeInfo().Assembly.GetTypes()14. Where(x => x.GetInterfaces().Any(y => y.GetTypeInfo().IsGenericType && y.GetGenericTypeDefinition() == mappingInterface));1516// Get the generic Entity method of the ModelBuilder type17var entityMethod = typeof(ModelBuilder).GetMethods()18. Single(x => x.Name == "Entity" &&19 x.IsGenericMethod &&20 x.ReturnType.Name == "EntityTypeBuilder`1");2122foreach (var mappingType in mappingTypes)23 {2425// Get the type of entity to be mapped26var genericTypeArg = mappingType.GetInterfaces().Single().GenericTypeArguments.Single();2728// Get the method builder.Entity<TEntity>29var genericEntityMethod = entityMethod.MakeGenericMethod(genericTypeArg);3031// Invoke builder.Entity<TEntity> to get a builder for the entity to be mapped32var entityBuilder = genericEntityMethod.Invoke(builder, null);3334// Create the mapping type and do the mapping35var mapper = Activator.CreateInstance(mappingType);36 mapper.GetType().GetMethod("Configure").Invoke(mapper, new[] { entityBuilder });37 }38foreach (var relationship in builder.Model.GetEntityTypes().SelectMany(e => e.GetForeignKeys()))39 {40 relationship.DeleteBehavior = DeleteBehavior.Restrict;41 }42 }43 }
View Code

Three, support:

support isn't meant for multiple database operatio &, of course, and later, we'll try to work on multiple database operatio & at the same time, which may require multiple contexts, regardless of whether or not. Distributed database. Our project might be sql server developed on windows, and we're publishing to linux, and sql server 2017 is said to support liunx, but no. It isn't said that sql server can be installed on liunx, but we would like to have or installed, we want to use existing, or, we need to switch the database. So, we need to switch the database support at any time, and the above MySQL for example:

1. Reference packages, MySQL I use pomelo, entityframeworkcore, mysql, and the, MySQL for,, ef.

A 2. 0 version ( install-package Pomelo.EntityFrameworkCore.MySql -version 2.0.0 -rtm-10059 ) needs to be specified in core 2.0.

2. You need to change the profile to dynamically load the database according to the related configuration. Related code and configuration are as follows

Redis reference list

1 <ItemGroup>2 <PackageReference Include="Microsoft.EntityFrameworkCore" Version="2.0.0"/>3 <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="2.0.0"/>4 <PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="2.0.0"/>5 <PackageReference Include="Pomelo.EntityFrameworkCore.MySql" Version="2.0.0-rtm-10058"/>6 </ItemGroup>
View Code

Related profile changes

"ConnectionStrings": {
 "MongoDbConnectionString": "mongodb://tchistory:tc123456@127.0.0.1/history",
 "ConnectionString": "Data Source=127.0.0.1;Initial Catalog=farmdata;User ID=root;Password=123456",
 "DataProvider": "MySql" },

Adding a database context in the ConfigureServices method of the startup. Cs.

publicvoid ConfigureServices(IServiceCollection services)
 {
 services.AddDbContext<DefaultContext>(option => option.UseFarmDatabase(Configuration));
 services.UseFarmService(Configuration);
 services.AddMvc();
 }

The database provides an object exte & ion method:

Public static dbcontextoptionsbuilder usefarmdatabase ( this dbcontextoptionsbuilder OptionsBuilder, IConfiguration configuration )
%.
String provider = configuration. GetConnectionString ("dataprovider"), connection = configuration. GetConnectionString ("connectionstring").
If ( provider. Equals ( databaseserver, sql server, StringComparison ) ).
%.
Return OptionsBuilder. UseSqlServer ( connection ).
%.
Else if ( provider. Equals ( databaseserver. Mysql, StringComparison, InvariantCultureIgnoreCase ) ).
%.
Return OptionsBuilder. Usemysql ( connection ).
%.
else
%.
Throw error. Argument ("usedatabaseserver","no DatabaseProvider").
%.
%.

Add a related migration command add-migration init at the package management co ole: generate a related migration directory under the current directory

Update database verbose commit changes to the database so that the database migration and changes are complete, where some of the databases in ef core 2.0 provide the object isn't fully implemented, such as pomelo. Entityframeworkcore. Mysql -version 1.1.2 may report the method not implemented, update 2. 0 rtm ve & ion.

Hopefully, the more smooth you're on the road;




Copyright © 2011 Dowemo All rights reserved.    Creative Commons   AboutUs