EF Code First table naming issues

做~自己de王妃 提交于 2020-01-06 08:38:09

问题


I have a project built using EF code first. It also uses forms authentication. Until recently the membership database and the application database were being developed separately, but I want to combine them into one database for simplicity.

One of the classes in my code first model is called "Application" so the EF-generated table is called "Applications" which conflicts with a membership table of the same name. This is an example of my current context:

public partial class ExampleContext : DbContext
{
    public DbSet<Application> Applications { get; set; }
    public DbSet<Status> StatusTypes { get; set; } // notice the name of the property vs the name of the class
}

I thought the table names were based on the names of the properties in the context, because it was generating a table named StatusTypes for all of the Status objects. But if I rename the Applications property to something like MyApplications it is still generating a table named Applications. So clearly it's not just the name of the property and I'm missing something.

My question: how do I get EF to name this table differently?


回答1:


Couldn't you use the configuration class to do something like this:

public class ApplicationConfiguration : EntityTypeConfiguration<Application>
{
    public ClientConfiguration()
    {
        ToTable("SpecialApplication");
    }
}

Then in your context override OnModelCreating:

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Configurations.Add(new ApplicationConfiguration());
    }

This should then force your table to be named SpecialApplication and avoid the conflict




回答2:


By default, Entity framework code first will generate pluralized names for tables when it builds the db from the model classes. You can override the OnModelCreating method of your db context class specify a different name for the table.

public class YourDBCOntext:DbContext
{
  protected override void OnModelCreating(DbModelBuilder modelBuilder)
  {
    modelBuilder.Entity<Applications>().ToTable("MYApplications");
  }    
}

You can do this globally also so that none of the tables will have pluralized names.

  protected override void OnModelCreating(DbModelBuilder modelBuilder)
  {
     modelBuilder.Conventions.Remove<PluralizingTaleNameConvention>();
  }    
}



回答3:


I just renamed the class and it worked. Easiest solution for now.



来源:https://stackoverflow.com/questions/12939091/ef-code-first-table-naming-issues

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!