问题描述
我想创建一个简单的实体框架code首次应用。我有这些类:
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; }
}
当我尝试创建一个新用户,并将其保存到数据库(用户没有ActivationTicket这是)我收到一个异常
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
INSERT语句冲突与外键约束ActivationTicket_User。发生在数据库中的测试,表dbo.ActivatioTickets,列ActivationTicketId的冲突。该语句已终止。
我想EF对待用户和ActivationTicket之间的映射为1-1,但它应该是1-0..1
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?
推荐答案
您将需要一个像这样的映射规则:
You will need a mapping rule like this:
modelBuilder
.Entity<User>()
.HasOptional<ActivationTicket>(u => u.ActivationTicket)
.WithOptionalPrincipal();
这会给你一个ActivationTickets表用户ID是空。
This will give you an ActivationTickets table with a UserId that is nullable.
这篇关于如何获得实体框架code第一,可为空的外键属性的工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!