Search code examples
c#entity-frameworkef-code-firstnullable

Nullable Properties in EF Code First?


I hope everyone remembers the Northwind database. As it has an Employee table which has a self-reference to itself. The Foreign Key is named 'ReportTo' or something like that which in turn is a Nullable field.

I am trying to implement such a table for a project in hand using EF Code First plus MVC3. The scenario is that: There is a Man class from which the User is derived. The mentioned field 'ReportTo' is set on the latter class (User). Here is the POCO:

[LocalizedAttribute("ReportTo")]
    public long ReportsTo { get; set; }
    [ForeignKey("ReportsTo")]
    public virtual IList<User> ReportsChild { get; set; }

But EF generated this field as 'Not Null' in the Database. I have tried to use ? exactly after IList<User>, which looks like IList<User>? that generates an error. I have also tried to define it as fluent API as:

modelBuilder.Entity<User>().Property(s => s.ReportsChild).IsOptional();

But both above ways give me this error:

The type 'System.Collections.Generic.IList' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'System.Nullable'

I've surfed the web but I could just find similar solutions as what I've done already.

What might be the reason? If I change IList<User> into User, would it still work correctly as the Foreign key? How can I get ride of this error?


Solution

  • You must wrirte as follow

     public Nullable<long> ReportsTo { get; set; }
    

    EDIT

    public long? ReportsTo { get; set; }