简体   繁体   中英

Entity Framework DisplayName is not the Table Name

I am currently in the process of upgrading .NET RC1 to RTM. As part of the upgrade process, I have to upgrade Entity Framework from 7.0.0-rc1 to 1.0.0. The process is described here and is pretty straightforward. As part of that process, there was a change to the table naming conventions .

I adding the corresponding code to OnModelCreating in my context.

foreach (var entity in builder.Model.GetEntityTypes())
{
    entity.Relational().TableName = entity.DisplayName();
    //System.Diagnostics.Debug.WriteLine($"Model = {entity.Model}");
    //System.Diagnostics.Debug.WriteLine($"Name = {entity.Name}");
    //System.Diagnostics.Debug.WriteLine($"Model = {entity.DisplayName()}");
}

As you can see, I'm printing out some of the information because the mapping isn't happening correctly. In those outputs, the DisplayName is remaining the default. So, Gender (my model) does not map to GenderLookup (my table). If it changes anything, I am also using Data Annotations and the Fluent API for mapping my table names to my models (I never leave the default). I'm not sure how this plays into it. Like:

[Table("GenderLookup")]
public class Gender
{
   // ...
}

and

builder.Entity<ApplicationUser>().ToTable("PreExistingUser");

What might I be doing wrong here?

I continued my search for what might be going on, and discovered this announcement from Rowan Miller which stated the following:

Impact on existing apps

If you upgrade an app from RC1 to RC2, you have several options:

  • If you are generating the database from the model, you can scaffold a new migration to apply the naming changes (or drop and recreate the database if you are using EnsureCreated() rather than migrations).
  • Manually specify table names to match what was chosen in RC1. This can be done in OnModelCreating or with the [Table] attribute. See the docs for more info.
  • Use the code from the following section to bulk configure table names to match what was chosen in RC1.

After reading that, I dove back into my code and discovered that there were a couple tables that did not have the [Table] attribute or were not covered in OnModelCreating . (As my team is required to use those to prevent falling back on the defaults in the first place, this may have been missed in a review.)

Once I rectified that situation, everything worked as expected. I wanted to share in case anybody else ran across the same issue.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM