【问题标题】:OnModelCreating Entity Framework CoreOnModelCreating 实体框架核心
【发布时间】:2016-11-09 17:47:55
【问题描述】:

此代码在MVC 中,我需要在ASP.net Core 中执行类似的操作,使用Entity Framework CoreDataAnnotations(我已经将参数从DbModelBuilder(MVC Entity Framework) 更改为ModelBuilder(Entity Framework Core) )

 protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>(); //error: Conventions is not recognized
            base.OnModelCreating(modelBuilder);
            modelBuilder.Entity<tbl_Line>()
                .HasMany(d => d.tbl_Policy)
                .WithRequired(c => c.tbl_Line) //error WithRequired not recognized
                .HasForeignKey(c => c.int_lineID);
        }

我尝试在Entity Framework Core中使用时出现一些错误:

1-'ModelBuilder' does not contain a definition for 'Conventions' and no extension method 'Conventions' accepting a first argument of type 'ModelBuilder' could be found (are you missing a using directive or an assembly reference?)

2-'CollectionNavigationBuilder&lt;tbl_Line, tbl_Policy&gt;' does not contain a definition for 'WithRequired' and no extension method 'WithRequired' accepting a first argument of type 'CollectionNavigationBuilder&lt;tbl_Line, tbl_Policy&gt;' could be found (are you missing a using directive or an assembly reference?)

【问题讨论】:

  • 一个好的起点 - EF Core vs. EF6.x
  • @IvanStoev 页面未找到。甚至我想使用配置在我的 ef 核心上下文文件中添加一个映射。在同一个文件中编写映射看起来很乱。有没有办法,或者需要像 AlexGh 那样添加它。
  • @nakulchawla09 最近的文档是here。不久,EF Core 中仍然不支持约定和/或配置,就像在 EF6 中一样(AFAIK 有计划添加,但我不知道什么时候),所以现在你被modelBuilder 卡住了。跨度>
  • 谢谢@IvanStoev。现在将使用模型构建器。叹息……

标签: c# asp.net-mvc entity-framework asp.net-core


【解决方案1】:

在支持 ModelBuilder.Configurations 之前,我使用扩展方法模拟旧的 Entity Framework 构造:

public static EntityTypeBuilder<Project> Map(this EntityTypeBuilder<Project> cfg)
{
    cfg.ToTable("sql_Projects");

    // Primary Key
    cfg.HasKey(p => p.Id);

    cfg.Property(p => p.Id)
        .IsRequired()
        .HasColumnName("ProjectId");

    return cfg;
}

然后像这样从 OnModelCreating 调用它...

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<Project>().Map();
    base.OnModelCreating(modelBuilder);
}

这有点笨拙,但我认为比尝试在主 DbContext 中配置数十个实体更干净。

【讨论】:

  • 这个方法好像不存在。
  • 你指的是哪种方法?