Dowemo

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





 1 public partial class Language : BaseEntity<int>


 2  {


 3 private ICollection<LocaleStringResource> _localeStringResources;


 4 


 5 /// <summary>


 6 /// Gets or sets the name


 7 /// </summary>


 8 


 9 public string Name { get; set; }


10 


11 /// <summary>


12 /// Gets or sets the language culture


13 /// </summary>


14 


15 public string LanguageCulture { get; set; }


16 


17 /// <summary>


18 /// Gets or sets the unique SEO code


19 /// </summary>


20 


21 public string UniqueSeoCode { get; set; }


22 


23 /// <summary>


24 /// Gets or sets the flag image file name


25 /// </summary>


26 


27 public string FlagImageFileName { get; set; }


28 


29 /// <summary>


30 /// Gets or sets a value indicating whether the language supports"Right-to-left"


31 /// </summary>


32 


33 public bool Rtl { get; set; }


34 


35 


36 /// <summary>


37 /// Gets or sets a value indicating whether the language is published


38 /// </summary>


39 


40 public bool Published { get; set; }


41 


42 /// <summary>


43 /// Gets or sets the display order


44 /// </summary>


45 


46 public int DisplayOrder { get; set; }


47 


48 public bool IsDefault { get; set; }


49 


50 /// <summary>


51 /// Gets or sets locale string resources


52 /// </summary>


53 public virtual ICollection<LocaleStringResource> LocaleStringResources


54  {


55 get { return _localeStringResources?? (_localeStringResources = new HashSet<LocaleStringResource>()); }


56 protected set { _localeStringResources = value; }


57 }





View Code

Language resources ( localestringresource ):





 1 public partial class LocaleStringResource : BaseEntity<int>


 2  {


 3 /// <summary>


 4 /// Gets or sets the language identifier


 5 /// </summary>


 6 public int LanguageId { get; set; }


 7 


 8 /// <summary>


 9 /// Gets or sets the resource name


10 /// </summary>


11 public string ResourceName { get; set; }


12 


13 /// <summary>


14 /// Gets or sets the resource value


15 /// </summary>


16 public string ResourceValue { get; set; }


17 


18 /// <summary>


19 /// Gets or sets a value indicating whether this resource was installed by a plugin


20 /// </summary>


21 public bool? IsFromPlugin { get; set; }


22 


23 /// <summary>


24 /// Gets or sets a value indicating whether this resource was modified by the user


25 /// </summary>


26 public bool? IsTouched { get; set; }


27 


28 /// <summary>


29 /// Gets or sets the language


30 /// </summary>


31 public virtual Language Language { get; set; }


32 


33 }





View Code

The language and resource primary key relationships are configured as follows





 1 public partial class LanguageMapper : IEntityTypeConfiguration<Language>


 2  {


 3 public void 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




 public partial class LocaleStringResourceMapper : IEntityTypeConfiguration<LocaleStringResource>


 {


 public void 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:





 1 public class TechCategory:BaseEntity<int>


 2  {


 3 /// <summary>


 4 /// 名称


 5 /// </summary>


 6 public string Name { get; set; }


 7 /// <summary>


 8 /// 分类描述


 9 /// </summary>


10 public string Descript { get; set; }


11 /// <summary>


12 /// meta标题


13 /// </summary>


14 public string MetaTitle { get; set; }


15 /// <summary>


16 /// meta描述


17 /// </summary>


18 public string MetaDescript { get; set; }


19 /// <summary>


20 /// 缩略图


21 /// </summary>


22 public string Thumb { get; set; }


23 /// <summary>


24 /// 图片


25 /// </summary>


26 public string Image { get; set; }


27 /// <summary>


28 /// 排序


29 /// </summary>


30 public int Sort { get; set; }


31 /// <summary>


32 /// 父级分类


33 /// </summary>


34 public int? ParentId { get; set; }


35 


36 /// <summary>


37 /// 父级分类


38 /// </summary>


39 


40 public virtual TechCategory Parent { get; set; }


41 public virtual ICollection<Technology> Technologys { get; set; }


42 /// <summary>


43 /// 子级


44 /// </summary>


45 public virtual ICollection<TechCategory> Childs { get; set; }


46 /// <summary>


47 /// 关键词


48 /// </summary>


49 public string Slug { get; set; }


50 /// <summary>


51 /// 创建时间


52 /// </summary>


53 public long CreatedOn { get; set; }


54 }





View Code




 1 public class TechCategoryMapper : IEntityTypeConfiguration<TechCategory>


 2  {


 3 public void 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





 1 public class DefaultContext : DbContext


 2  {


 3 public DefaultContext(DbContextOptions<DefaultContext> opt)


 4 :base(opt)


 5  {


 6 AutoCommitEnabled = true;


 7  }


 8 protected override void OnModelCreating(ModelBuilder builder)


 9  {


10 base.OnModelCreating(builder);


11 var mappingInterface = typeof(IEntityTypeConfiguration<>);


12 // Types that do entity mapping


13 var mappingTypes = GetType().GetTypeInfo().Assembly.GetTypes()


14. Where(x => x.GetInterfaces().Any(y => y.GetTypeInfo().IsGenericType && y.GetGenericTypeDefinition() == mappingInterface));


15 


16 // Get the generic Entity method of the ModelBuilder type


17 var entityMethod = typeof(ModelBuilder).GetMethods()


18. Single(x => x.Name == "Entity" &&


19 x.IsGenericMethod &&


20 x.ReturnType.Name == "EntityTypeBuilder`1");


21 


22 foreach (var mappingType in mappingTypes)


23  {


24 


25 // Get the type of entity to be mapped


26 var genericTypeArg = mappingType.GetInterfaces().Single().GenericTypeArguments.Single();


27 


28 // Get the method builder.Entity<TEntity>


29 var genericEntityMethod = entityMethod.MakeGenericMethod(genericTypeArg);


30 


31 // Invoke builder.Entity<TEntity> to get a builder for the entity to be mapped


32 var entityBuilder = genericEntityMethod.Invoke(builder, null);


33 


34 // Create the mapping type and do the mapping


35 var mapper = Activator.CreateInstance(mappingType);


36 mapper.GetType().GetMethod("Configure").Invoke(mapper, new[] { entityBuilder });


37  }


38 foreach (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.





 public void 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