OnModelCreating Entity Framework Core
Until there is support for ModelBuilder.Configurations I emulate the older Entity Framework construction with extension methods:
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;
}
and then call it from OnModelCreating like this...
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Project>().Map();
base.OnModelCreating(modelBuilder);
}
It is a bit clumsy, but cleaner, I think, than trying to configure dozens of entities within the main DbContext.
Related videos on Youtube
AlexGH
Updated on July 25, 2022Comments
-
AlexGH almost 2 years
This code is in
MVC
, I need to do something like this but inASP.net Core
, usingEntity Framework Core
, or withDataAnnotations
(I've changed the parameter already fromDbModelBuilder(MVC Entity Framework)
toModelBuilder(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); }
There are some errors when I'm trying to use it in
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?)
-
Ivan Stoev over 7 yearsA good starting point - EF Core vs. EF6.x
-
-
Nathan McKaskle over 6 yearsThis method doesn't seem to exist.
-
Neilski over 6 yearsWhich method are you referring to?