【问题标题】:How to save an identity value of one table to foreign key of another table in entity framework?如何将一个表的标识值保存到实体框架中另一个表的外键?
【发布时间】:2015-01-29 12:04:14
【问题描述】:

我有两张桌子:useruserprofile

User 有一个列 id 这是一个 identity 并且是主键

UserprofileuserId 列,它是 user.id 的外键。

context.User.Add(userModel);
context.UserProfile.Add(userprofileMode);
context.SaveChanges();

但是当我执行user.id = userprofile.Userid 时,它不会保存值,因为它是标识列。 Entity Framework中如何将user表id的值保存到userprofile表的userid中?

【问题讨论】:

  • 你能发布你的模型吗?

标签: asp.net-mvc entity-framework


【解决方案1】:

您不会 - 不要尝试在上下文中添加 UserUserProfile 并手动执行密钥。你会做这样的事情:

User userModel = new userModel() {
  // Set properties
}

userModel.Profile = new UserProfile() {
  // Set properties
}

context.User.Add(userModel);
context.SaveChanges();

Entity Framework 会自动对键进行排序。只需简单地将 UserProfile 添加到正确的导航属性,将用户添加到您的上下文中,然后保存即可。

【讨论】:

  • 只是为了教育价值,需要这样做的原因是User在实际保存到数据库之前实际上不会有id值,这不会发生直到SaveChanges 被调用。您可以添加User,保存,然后为UserProfile 设置外键并再次保存,但这只会增加不必要的工作和开销。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-03-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-07-05
  • 1970-01-01
相关资源
最近更新 更多