从EF6迁移到EF Core 2.0

时间:2018-03-07 08:36:23

标签: c# entity-framework-core ef-fluent-api ef-core-2.0

我刚刚开始将我的MVC5项目与EF6x一起移植到MVC Core和EF Core,但我的实体配置存在很大问题。如何将EF6 Fluent配置迁移到EF核心?
如果可能的话,我需要带样本的指南。

这是我的一个映射类和我的尝试

EntityMappingConfiguratuin

public interface IEntityMappingConfiguration
{
    void Map(ModelBuilder b);
}

public interface IEntityMappingConfiguration<T> : EntityMappingConfiguration where T : class
{
    void Map(EntityTypeBuilder<T> builder);
}

public abstract class EntityMappingConfiguration<T> : EntityMappingConfiguration<T> where T : class
{
    public abstract void Map(EntityTypeBuilder<T> b);

    public void Map(ModelBuilder b)
    {
        Map(b.Entity<T>());
    }
}

public static class ModelBuilderExtenions
{
    private static IEnumerable<Type> GetMappingTypes(this Assembly assembly, Type mappingInterface)
    {
        return assembly.GetTypes().Where(x => !x.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(IEntityMappingConfiguration<>));
        foreach (var config in mappingTypes.Select(Activator.CreateInstance).Cast<IEntityMappingConfiguration>())
        {
            config.Map(modelBuilder);
        }
    }
}

的DbContext

public class CommerceServiceDbContext : AbpDbContext
    {
        public CommerceServiceDbContext(DbContextOptions<CommerceServiceDbContext> options) 
            : base(options)
        {
        }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.AddEntityConfigurationsFromAssembly(GetType().Assembly);
        }
    }

简单的旧配置

public partial class AffiliateMap : EntityMappingConfiguration<Affiliate>
{
    public override void Map(EntityTypeBuilder<Affiliate> b)
    {
        b.ToTable("Affiliate");
        b.HasKey(a => a.Id);
        b.HasRequired(a => a.Address).WithMany().HasForeignKey(x => x.AddressId).WillCascadeOnDelete(false);
    }
}

我的尝试

public partial class AffiliateMap : EntityMappingConfiguration<Affiliate>
{
    public override void Map(EntityTypeBuilder<Affiliate> b)
    {
        b.ToTable("Affiliate");
        b.HasKey(a => a.Id);
        b.HasOne(a => a.Address)
            .WithMany().HasForeignKey(x => x.AddressId).IsRequired().OnDelete(DeleteBehavior.Restrict);
    }

}

我使用Google搜索和Microsoft文档完成了此操作。但我不确定我的工作。由于我有+100配置类,我会在继续之前问你。如果我的问题内容与网站的条款和条件不符,我很抱歉。

1 个答案:

答案 0 :(得分:16)

我发现了一篇关于迁移到EF核心的好文章。我希望与像我这样的初学者分享并保留这个问题。

代码更新
命名空间System.Data.Entity已替换为Microsoft.EntityFrameworkCore
HasDatabaseGeneratedOption(DatabaseGeneratedOption.None)替换为ValueGeneratedNever(); DbContext的基础构造函数没有连接字符串的单个字符串参数。我们现在必须注入DbContextOptions
OnModelCreating(DbModelBuilder modelBuilder)变为OnModelCreating(ModelBuilder modelBuilder)。简单的改变,但改变所有相同的 modelBuilder.Configurations.AddFromAssembly(Assembly.GetExecutingAssembly());已不再可用,这意味着EntityTypeConfiguration也不可用,因此我必须将所有实体配置移至OnModelCreating
((IObjectContextAdapter)context).ObjectContext.ObjectMaterialized已不再可用。我正在使用它来扩展DbContext以将out中的所有日期转换为Utc。我还没有找到替代品 ComplexType已不再可用。我不得不稍微改变一下模型结构以适应这个 MigrateDatabaseToLatestVersion已不再可用,因此我必须将以下内容添加到我的startup.cs中

using (var serviceScope = app.ApplicationServices.GetRequiredService<IServiceScopeFactory>().CreateScope())
{
    serviceScope.ServiceProvider.GetService<SbDbContext>().Database.Migrate();
}

WillCascadeOnDelete(false)变为OnDelete(DeleteBehavior.Restrict)
根据帖子,HasOptional已不再相关 IDbSet成为DbSet
DbSet<T>.Add()不再返回T,而是EntityEntry<T>

var entry = context.LearningAreaCategories.Add(new LearningAreaCategory());
//that's if you need to use the entity afterwards
var entity = entry.Entity;

IQueryable<T>.Include(Func<>)现在返回IIncludableQueryable<T,Y>而不是IQueryable<T>,同样适用于OrderBy。我所做的是将所有包含和订单移动到最后。

来源:Moving from EF6 to EF Core