如何将一个 table 的标识值保存到 entity framework 中另一个 table 的外键?

How to save an identity value of one table to foreign key of another table in entity framework?

我有两个 table:useruserprofile

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

UserprofileuserId 列,它是 user.id.

的外键
context.User.Add(userModel);
context.UserProfile.Add(userprofileMode);
context.SaveChanges();

但是当我执行 user.id = userprofile.Userid 时,它不会保存值,因为它是标识列。如何将用户 table 的 ID 值保存到 Entity Framework 中用户配置文件 table 的用户 ID?

你不会 - 不要尝试将 UserUserProfile 添加到上下文并手动执行键。你会做类似的事情:

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

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

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

Entity Framework 会自动整理出key。只需将 UserProfile 添加到正确的导航 属性,将用户添加到您的上下文,然后保存即可。