自己编写 EntityTypeConfiguration

1.新建类库 EFCore.EntityTypeConfig ,安装nuget  PM> Install-Package Microsoft.EntityFrameworkCore

自己编写 EntityTypeConfiguration

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);
}
}

IEntityTypeConfiguration

新建类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>());
}
}
}

EntityTypeConfiguration.cs

新建类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); }
}
}
}

ModelBuilderExtenions.cs

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

上一篇:Java第二次实训


下一篇:PYQT5登录界面跳转主界面方法