Reputation: 15229
I see the CodeFirst in EF Core generates the table names from the DbSet names of the DbContext.
If I have DbSet<Person> People {get; set;}
I will get the People
as table name for Person
, however I would like it to be Person
.
I tried this solution, but it seems it not for the Core...
After that I tried
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
foreach (var entity in modelBuilder.Model.GetEntityTypes())
{
modelBuilder.Entity(entity.Name)
.ToTable(entity.Name);
}
}
This is better, but it gives me the full name of the class with the namespace, is there a way to remove the namespace from it?
Upvotes: 0
Views: 2903
Reputation: 320
I was using this approach and found it failed when there was a many to many relationship in the DbContext. Ef Core would create an internal entity to do the many-to-many join and that would error out on the above code.
In order to over come that I changed the code to below. Warning: This uses EF Core internal API and may break in the future as EF Core evolves
foreach (EntityType entity in modelBuilder.Model.GetEntityTypes())
{
if (!entity.IsImplicitlyCreatedJoinEntityType)
{
modelBuilder.Entity(entity.ClrType).ToTable(entity.ClrType.Name);
}
}
Upvotes: 1
Reputation: 672
You can also annotate your class with an attribute specifying your desired table name. This is extremely useful when you follow a specific pattern of table names:
using System;
using System.ComponentModel.DataAnnotations.Schema;
namespace YourProject.YourPackage
{
[Table("tblPerson")]//this is how the table will be called in the database. You can also specify a schema if needed
public class Person
{
//your properties here
}
}
Upvotes: 2
Reputation: 15229
Use DisplayName()
instead of Name
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
foreach (var entity in modelBuilder.Model.GetEntityTypes())
{
modelBuilder.Entity(entity.Name)
.ToTable(entity.DisplayName());
}
}
Upvotes: 1