First Multi Column Foreign Key in Entity Framework

c# ef-code-first entity-framework sql

Question

I made 3 classes using code first:

class User {     

 public Int32 ID {get;set;}  

 public virtual ICollection<UserCityDetail> {get;set;}

 public Int32 MainCityID {get;set;}
 public UserCityDetail MainCityDetail {get;set;}

}

class City{

 public Int32 ID {get;set;}

 ...
}

class UserCityDetail{

 [Key, Column(Order = 0)]
 public Int32 UserID {get;set;}

 [Key, Column(Order = 1)]
 public Int32 CityID{get;set;}

 ...
}

So in essence, I have a user that has various data on a number of cities. UserCityDetail reports that User ID is both PK and FK. I've added a city ID FK to User since I also want to have a direct link to the primary city information.

How can User ID and MainCityID be set up such that they behave like FK for MainCityDetail?

1
5
5/1/2012 10:36:29 AM

Popular Answer

Given that there are two connections betweenUser and UserCityDetail The identification of which navigational features correspond to which connection is a challenge for EF. To map the relationships, use the fluent API.

If you are using SQL Server, there would be an additional issue since two relationships results in numerous cascade delete routes. Thus, you must createMainCityDetail an optional connection.

class User {     

 public Int32 ID {get;set;}  

 public virtual ICollection<UserCityDetail> {get;set;}

 public int? MainCityUserID {get;set;}
 public int? MainCityID {get;set;}

 public UserCityDetail MainCityDetail {get;set;}

}


public class MyContext : DbContext
{
    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);

        modelBuilder.Entity<User>()
            .HasOptional(u => u.MainCityDetail)
            .WithMany()
            .HasForeignKey(u => new { u.MainCityUserID, u.MainCityID})
            .WillCascadeOnDelete(false);

        modelBuilder.Entity<User>()
            .HasMany(u => u.Cities)
            .WithRequired(d => d.User)
            .HasForeignKey(d => d.UserId);
    }
}

Check out here for further information about fluent mappings.

8
5/1/2012 11:04:25 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow