[英]How to set null foreign key in Entity Framework code-first
I have a Order < Customer model. 我有一个订单<客户模型。
How do I set this up? 我该如何设置? When I try to insert a user with a null customerid, it tells me that it cannot be null.
当我尝试插入一个客户ID为空的用户时,它告诉我不能为空。
The model is as follows: 该模型如下:
public class Order
{
public long OrderID { get; set; }
public int CustomerID { get; set; }
public virtual Customer Customer { get; set; }
public virtual ICollection<OrderDetail> OrderDetails { get; set; }
}
public partial class Customer
{
public int CustomerID { get; set; }
}
In DbContext
: 在
DbContext
:
modelBuilder.Entity<Customer>()
.HasMany(e => e.Orders)
.WithRequired(e => e.Customer)
.WillCascadeOnDelete(false);
Have you tried to replace line 您是否尝试过更换线
.WithRequired(e => e.Customer)
with 与
.WithOptional(e => e.Customer)
? ?
And I make the CustomerID property nullable: public int? 我将CustomerID属性设置为可空:public int? CustomerID { get;
客户ID {get; set;
组; }
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.