如何使实体框架代码优先和可为空的外键属性起作用?
我正在尝试创建一个简单的实体框架代码优先应用程序。我有这些类:
public class User
{
public int UserId { get; set; }
public string Username { get; set; }
public virtual ActivationTicket ActivationTicket { get; set; }
}
public class ActivationTicket
{
public int ActivationTicketId { get; set; }
public virtual User User { get; set; }
public string Ticket { get; set; }
}
当我尝试创建新用户并将其保存到数据库(即没有 ActivationTicket 的用户)时,我收到异常
INSERT 语句与 FOREIGN KEY 约束“ActivationTicket_User”冲突。冲突发生在数据库“Test”、表“dbo.ActivatioTickets”、列“ActivationTicketId”中。该声明已终止。
我假设 EF 将 User 和 ActivationTicket 之间的映射视为 1-1,但它应该是 1-0..1
我需要做什么才能使其正常工作?
I'm trying to create a simple entity framework code first application. I have these classes:
public class User
{
public int UserId { get; set; }
public string Username { get; set; }
public virtual ActivationTicket ActivationTicket { get; set; }
}
public class ActivationTicket
{
public int ActivationTicketId { get; set; }
public virtual User User { get; set; }
public string Ticket { get; set; }
}
When I try to create a new user and save it to the database (a user without a ActivationTicket that is) I receive an exception
The INSERT statement conflicted with the FOREIGN KEY constraint "ActivationTicket_User". The conflict occurred in database "Test", table "dbo.ActivatioTickets", column 'ActivationTicketId'. The statement has been terminated.
I assume EF treats the mapping between User and ActivationTicket as 1-1 but it should be 1-0..1
What do I have to do to get this to work?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您将需要这样的映射规则:
这将为您提供一个 ActivationTickets 表,其中的 UserId 可以为空。
You will need a mapping rule like this:
This will give you an ActivationTickets table with a UserId that is nullable.
@b3n
这样做应该足够了,至少在 VS 2013 中是这样:
这是重要的部分:
这将在“User”表中为 ActivationTicket 指定外键,并定义它是可选的。
学分转到:
http:// forums.asp.net/t/1948351.aspx?Change+Foreign+Key+to+nullable+using+Code+First#5554732
我遇到了同样的问题,它立即对我有用。
另外,作为注释,我用数据注释“[Key]”标记了所有主键。为了使这项工作顺利进行,这可能是必要的。
@b3n
It should be enough to do this, at least with VS 2013:
This is the important part:
This will specify the foreignkey in your "User" table for the ActivasionTicket and define that it's optional.
credits go to:
http://forums.asp.net/t/1948351.aspx?Change+Foreign+Key+to+nullable+using+Code+First#5554732
I had the same problem and it instantly worked for me.
Also as a note i marked all my primary keys with the data annotation "[Key]". This might be necessary in order to make this work.