标签:sel mod server sre sys pen col protected none
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"); } } }
标签:sel mod server sre sys pen col protected none
原文地址:http://www.cnblogs.com/qq605490312/p/7799388.html