如何在实体框架代码中首先设置null外键

时间:2017-02-26 03:51:15

标签: c# entity-framework

我有一个订单<客户模式。

如何设置?当我尝试插入具有null customerid的用户时,它告诉我它不能为空。

模型如下:

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; }   
}

DbContext

modelBuilder.Entity<Customer>()
            .HasMany(e => e.Orders)
            .WithRequired(e => e.Customer)
            .WillCascadeOnDelete(false);

1 个答案:

答案 0 :(得分:1)

您是否尝试过替换

.WithRequired(e => e.Customer)

.WithOptional(e => e.Customer)

我将CustomerID属性设为可空:public int? CustomerID {get;组; }