开发者

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

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 { g开发者_开发知识库et; 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?


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.


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"));
  }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜