serge
serge

Reputation: 15229

EF Core how to map table names to Entity names, not DbSet names?

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

Answers (3)

Brett Manners
Brett Manners

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

josibu
josibu

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

serge
serge

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

Related Questions