EF 4.1 messing things up. Has FK naming strategy changed?

流过昼夜 提交于 2019-11-28 00:06:03

问题


I've just installed the new Entity Framework 4.1 NuGet package, thus replacing the EFCodeFirst package as per NuGet intructions and this article of Scott Hanselman.

Now, imagine the following model:

public class User
{
    [Key]
    public string UserName { get; set; }
    // whatever
}

public class UserThing
{
    public int ID { get; set; }
    public virtual User User { get; set; }
    // whatever
}

The last EFCodeFirst release generated a foreign key in the UserThing table called UserUserName.

After installing the new release and running I get the following error:

Invalid column name 'User_UserName'

Which of course means that the new release has a different FK naming strategy. This is consistent among all other tables and columns: whatever FK EFCodeFirst named AnyOldForeignKeyID EF 4.1 wants to call AnyOldForeignKey_ID (note the underscore).

I don't mind naming the FK's with an underscore, but in this case it means having to either unnecessarily throw away the database and recreate it or unnecessarily renaming al FK's.

Does any one know why the FK naming convention has changed and whether it can be configured without using the Fluent API?


回答1:


Unfortunately, one of the things that didn't make it to this release is the ability to add custom conventions in Code First:

http://blogs.msdn.com/b/adonet/archive/2011/03/15/ef-4-1-release-candidate-available.aspx

If you don't want to use the fluent API to configure the column name (which I don't blame you), then most straight forward way to do it is probably using sp_rename.




回答2:


Why don't you do the following?

  public class User
  {
    [Key]
    public string UserName { get; set; }
    // whatever
  }

  public class UserThing
  {
    public int ID { get; set; }
    public string UserUserName { get; set; }
    [ForeignKey("UserUserName")]
    public virtual User User { get; set; }
    // whatever
  }

Or, if you don't want to add the UserUserName property to UserThing, then use the fluent API, like so:

// class User same as in question
// class UserThing same as in question

public class MyContext : DbContext
{
  public MyContext()
    : base("MyCeDb") { }
  public DbSet<User> Users { get; set; }
  public DbSet<UserThing> UserThings { get; set; }

  protected override void OnModelCreating(DbModelBuilder modelBuilder)
  {
    modelBuilder.Entity<UserThing>()
      .HasOptional(ut => ut.User)    // See if HasRequired fits your model better
      .WithMany().Map(u => u.MapKey("UserUserName"));
  }
}


来源:https://stackoverflow.com/questions/5344474/ef-4-1-messing-things-up-has-fk-naming-strategy-changed

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