0

I have to build a Code First DB and want to make a Foreign Key Nullable. But I dont know how to do it because it shows that this field can't be 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; }
    }
}

Product:

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

The Column i want to be null is Product !

  • Please post your error as text as [edit] of your question. Second: I think it's just a typo. – Stefan Jul 17 '18 at 08:26
  • Ah, you need to get rid of the `?`. Reference types can be `null` by design and don't need the `Nullable<>` or `?` syntax. – Stefan Jul 17 '18 at 08:27
  • @Stefan thanks :) silly that I did not think of that by myself –  Jul 17 '18 at 08:31

1 Answers1

0

To make it clear in your code, you could set the FK field in the Order_Item class explicitly:

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; }
    }
}
Matt Styles
  • 581
  • 1
  • 4
  • 14