如何制作可空FK EF

时间:2018-07-17 08:24:24

标签: c# entity-framework ef-code-first

我必须构建一个Code First数据库,并想使外键为空。但是我不知道该怎么办,因为它表明此字段不能为Null。

Error

Order_Item:

namespace ORDER_DATABASE.Tables
{
    public class Order_Item
    {
        public int Id { get; set; }
        public virtual Order Order { get; set; }
        public virtual Product Product { get; set; }
        public int Amount { get; set; }
    }
}

产品:

using System;
using System.Collections.Generic;

namespace ORDER_DATABASE.Tables
{
    public class Product
    {
        public int Id { get; set; }
        public virtual Supplier Supplier { get; set; }
        public virtual Category Category { get; set; }
        public String Name { get; set; }
        public int Price { get; set; }

        public virtual List<Order_Item> OrderItems { get; set; }
    }
}

我想为空的列是产品

1 个答案:

答案 0 :(得分:0)

为使代码清晰可见,您可以在Order_Item类中显式设置FK字段:

namespace ORDER_DATABASE.Tables
{
    public class Order_Item
    {
        public int Id { get; set; }
        public int Amount { get; set; }
        public int? ProductId { get; set; }

        public virtual Order Order { get; set; }
        public virtual Product Product { get; set; }
    }
}