当用户有多个导航属性时,哪个 FK 列由 EF 更新 table

Which FK column is update by EF when there are multiple navigation properties to Users table

场景

我有table喜欢

  1. 用户(ID, Email, Password)
  2. User_Profile (ID, UserID_FK, First, Last, Created_On, Created_By_FK)

这是我创建新用户帐户的方式

Users us = new Users 
{ 
    Email = 'xyz@example.com', 
    Password = 123 
};

User_Profile up = new User_Profile 
{
    First = 'Kamalpreet',
    Last = 'Singh',
    Created_On = DateTime.Now
};

us.User_Profile.Add(up);

Context x = new Context();
x.Users.Add(us);
db.Save();

以上代码在数据库中创建以下记录-

用户Table-

ID = 100
Email = xyz@example.com
Password = 123

User_Profile Table-

ID = 1
UserID_FK = 100
First = Kamalpreet
Last = Singh
Created_On = 2016-08-06 10:40:10.000
Created_By_FK = NULL

问题

在 User_Profile table 中,为什么 Users(ID) 只复制到 User_Profile(UserID_FK) table 而没有复制到 User_Profile(Created_By_FK)

UserID_FK 和 Created_By_FK 列都是对用户 (ID) 的外键引用 table。

当您首先生成数据库 DbContext 时,您会得到两个要添加的集合(如果您有两个关系设置 - 每个键一个)。例如,您应该会看到:

  1. us.User_Profile.Add()
  2. 我们.User_Profile2.Add()

然后您可以将配置文件添加到两个集合中,以便在持久化时正确更新两个外键。 Entity Framework 跟踪您已将相同对象引用添加到两个集合的事实,并将正确保存它。

注意:另一种选择是保存用户,然后把你得到的ID放在两个外键属性上,但这样效率可能较低。