gpt4 book ai didi

c# - OnModelCreating Entity Framework Core

转载 作者:行者123 更新时间:2023-12-04 03:16:29 30 4
gpt4 key购买 nike

此代码在 MVC 中,我需要在 ASP.net Core 中执行类似操作,使用 Entity Framework Core 或使用 DataAnnotations (我已经将参数从 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<tbl_Line, tbl_Policy>' does not contain a definition for 'WithRequired' and no extension method 'WithRequired' accepting a first argument of type 'CollectionNavigationBuilder<tbl_Line, tbl_Policy>' could be found (are you missing a using directive or an assembly reference?)

最佳答案

在支持 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 中配置数十个实体相比,这有点笨拙,但我认为更简洁。

关于c# - OnModelCreating Entity Framework Core,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40513060/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com