OnModelCreating实体框架核心
本文关键字:核心 框架 实体 OnModelCreating | 更新日期: 2023-09-27 18:17:13
这段代码是在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?)
'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的支持。配置我用扩展方法模拟旧的实体框架构造:
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中配置几十个实体更干净。