使用自动 ID 的实体框架外键插入
我有 2 个实体 User 和 User_Profile (一对一关系)。我将它们链接如下:
public class User
{
[Key]
[ForeignKey("user_profile")]
public int user_id {get;set;}
public string username {get;set;}
public string email {get;set;}
public virtual User_Proile user_profile {get;set;}
}
public class User_Profile
{
[Key]
public int user_id {get;set;}
public string firstname {get;set;}
public string lastname {get;set;}
}
user_id 是 SQL Server 的 User 和 User_Profile 表中的 PK。它还被设置为用户表中的身份列。
当我尝试通过 EFDBContext Add/SaveChanges 插入新记录时。我收到以下错误:“User_Profile 表中的 user_id 不能为 NULL” 这很有意义,因为这是一个 PK 列。我希望 EF 能够从用户中获取身份 user_id 并在保存时将其插入到 User_Profile user_id 中。
这可能吗?如果可以,我将如何实施?
更新:请注意,我手动创建了数据库表和代码类,因此我无法通过 .edmx 文件访问 StoreGeneratePattern。
I have 2 Entities User and User_Profile (one to one relationship). I have linked them as follows:
public class User
{
[Key]
[ForeignKey("user_profile")]
public int user_id {get;set;}
public string username {get;set;}
public string email {get;set;}
public virtual User_Proile user_profile {get;set;}
}
public class User_Profile
{
[Key]
public int user_id {get;set;}
public string firstname {get;set;}
public string lastname {get;set;}
}
user_id is a PK in both SQL Server's User and User_Profile tables. It is also set as an Identity column in the User table.
When I try to insert a new record via the EFDBContext Add/SaveChanges. I get the following error: "user_id cannot be NULL in the User_Profile table" This makes perfect sense as this is a PK column. I was hoping EF would be able to take the Identity user_id from Users and Insert it into User_Profile user_id when saving.
Is this possible and if so how would I implement that?
UPDATE: Please note that I manually created the DB tables and code classes so I dont have access to StoreGeneratedPattern via the .edmx file.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我认为有必要使用 Fluent API 显式配置一对一关系:
和实体类:
有必要关闭从
Identity
到的
。我已经交换了主体和依赖项,因为似乎DatabaseGenerateOption
其中一个类中没有User
应该是主体。[ForeignKey(...)]
不是必需的,因为 EF 会将User_Profile
中的user_id
识别为User< 的 FK 属性/代码>。
像这样的代码...
...应该按照您的预期工作并将两个相关实体保存到数据库中。
I think it is necessary to configure your one-to-one relationship explicitely using Fluent API:
And the entity classes:
It's necessary to switch off
DatabaseGeneratedOption
fromIdentity
toNone
in one of the classes. I have swapped principal and dependent as it seems that theUser
should be the principal. The[ForeignKey(...)]
is not necessary because EF will recognizeuser_id
inUser_Profile
as a FK property toUser
.A code like this...
...should work then as you expect and save both related entities to the database.
您必须在 .edmx 文件中将 StoreGeneratePattern 属性设置为 Identity,以使框架知道该字段是由数据库生成的。此链接可能会有所帮助...
使用实体框架自动编号
You have to set the StoreGeneratedPattern attribute to Identity in your .edmx file to let the framework know the field is generated by the database. This link might help...
Autonumber with Entity Framework