实体框架代码优先多列外键

实体框架代码优先多列外键

本文介绍了实体框架代码优先多列外键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用代码首先我设计了3类:

Using code first I designed 3 classes:

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;}

 ...
}

所以基本上我有有几个城市不同的细节的用户。
的用户ID是既PK和FK到UserCityDetail。我也希望有一个直接引用到主城的细节,所以我已经把一个城市的标识FK上的用户。

So basically I have a user that have different details on several cities.User ID is both PK and FK to UserCityDetail. I also want to have a direct reference to the main city details, so I've put a city ID FK on User.

如何配置用户ID和MainCityID行动象FK为MainCityDetail?

How to configure User ID and MainCityID to act like FK for MainCityDetail?

推荐答案

由于有用户之间的两个关系和 UserCityDetail 英孚已经确定的一个问题,导航性能属于其中的关系。使用流畅的API的关系映射。

Since there are two relationships between User and UserCityDetail EF has a problem of identifying which navigational properties belong to which relationship. Use the fluent API to map the relationships.

如果您使用的是SQL Server,因为两个关系导致多个级联删除路径会有另一个问题。所以,你必须让 MainCityDetail 可选的关系。

There would be another problem if you are using SQL Server because two relationships leads to multiple cascade delete paths. So you have to make MainCityDetail an optional relationship.

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

有关流利的映射更多的细节的。

For further details on fluent mappings check here.

这篇关于实体框架代码优先多列外键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-29 16:06