Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 { 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?

like image 744
Sergi Papaseit Avatar asked Mar 17 '11 19:03

Sergi Papaseit


2 Answers

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"));
  }
}
like image 39
Andre Artus Avatar answered Nov 12 '22 02:11

Andre Artus


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.

like image 121
Brian Ball Avatar answered Nov 12 '22 04:11

Brian Ball