自己编写 EntityTypeConfiguration
Posted 愚公学编程
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了自己编写 EntityTypeConfiguration相关的知识,希望对你有一定的参考价值。
1.新建类库 EFCore.EntityTypeConfig ,安装nuget PM> Install-Package Microsoft.EntityFrameworkCore
2.新建接口IEntityTypeConfiguration
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Metadata.Builders; using System; using System.Collections.Generic; using System.Text; namespace EFCore.EntityTypeConfig { public interface IEntityTypeConfiguration { void Map(ModelBuilder bulder); } public interface IEntityTypeConfiguration<T>:IEntityTypeConfiguration where T:class { void Map(EntityTypeBuilder<T> builder); } }
新建类EntityTypeConfiguration.cs
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Metadata.Builders; using System; using System.Collections.Generic; using System.Text; namespace EFCore.EntityTypeConfig { public abstract class EntityTypeConfiguration<T>:IEntityTypeConfiguration<T> where T:class { public abstract void Map(EntityTypeBuilder<T> builder); public void Map(ModelBuilder builder) { Map(builder.Entity<T>()); } } }
新建类ModelBuilderExtenions.cs
using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; namespace EFCore.EntityTypeConfig { public static class ModelBuilderExtenions { private static IEnumerable<Type> GetMappingTypes(this Assembly assembly, Type mappingInterface) { return assembly.GetTypes().Where(x => !x.GetTypeInfo().IsAbstract && x.GetInterfaces().Any(y => y.GetTypeInfo().IsGenericType && y.GetGenericTypeDefinition() == mappingInterface)); } public static void AddEntityConfigurationsFromAssembly(this ModelBuilder modelBuilder, Assembly assembly) { var mappingTypes = assembly.GetMappingTypes(typeof(IEntityTypeConfiguration<>)); foreach (var config in mappingTypes.Select(Activator.CreateInstance).Cast<IEntityTypeConfiguration>()) { config.Map(modelBuilder); } } } }
3.控制台引用类库EFCore.EntityTypeConfig
using EFCore.EntityTypeConfig; using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.Reflection; using System.Text; namespace ConsoleApp3 { public class MyDbContext:DbContext { public DbSet<Person> Persons { get; set; } protected override void OnModelCreating(ModelBuilder modelBuilder) { base.OnModelCreating(modelBuilder); // modelBuilder.Entity<Person>().ToTable("T_Persons").Property(e => e.Id).IsRequired(); // modelBuilder.Entity<Person>().ToTable("T_Persons") ; modelBuilder.AddEntityConfigurationsFromAssembly(Assembly.GetEntryAssembly()); } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { base.OnConfiguring(optionsBuilder); optionsBuilder.Usemysql("Server=127.0.0.1;database=test;uid=root;pwd=123321"); } } }
以上是关于自己编写 EntityTypeConfiguration的主要内容,如果未能解决你的问题,请参考以下文章