Using nullable for Foreign Key in Entity Framawork

asp.net-mvc c# entity-framework entity-framework-6 sql-server

Question

I use EF Code First approach in an ASP.NET MVC project and I have PK-FK relations on several entities as shown below:

public class Staff
{
    public int Id { get; set; }

    //Foreign key for Project
    public int ProjectId { get; set; }

    public virtual Project Project { get; set; }
}



public class Project
{
    public int Id { get; set; }

    public string Name { get; set; }

    public virtual ICollection<Staff> Staffs { get; set; }
}

On the other hand, sometimes there is a need to use nullable FK values and in that case I create dummy record as N/A as FK is required property that seems to em ugly :( I know I can easily use nullable value for the related FK property, but I am not sure if it is a good approach or not. And what is the pros and cons using this approach (I know a pros of required FK : Data integrity :)

Secondly, should I use 0 or null value for the nullable FK? Why?

1
0
9/9/2019 5:46:11 PM

Accepted Answer

Adding a dummy record is not right, the correct approach here is to use an int? for the foreign key relation, see here:

If the data type of GradeId is nullable integer, then it will create a null foreign key.

public class Student 
{
    public int Id { get; set; }
    public string Name { get; set; }

    public int? GradeId { get; set; }
    public Grade Grade { get; set; } 
}

The above code snippet will create a nullable GradeId column in the database because we have used Nullable<int> type (? is a shortcut for Nullable<int>)

An alternative approach would be removing ProjectId from the staff (Convention 3 in the above document):

public class Staff
{
    public int Id { get; set; }
    public virtual Project Project { get; set; }
}

public class Project
{
    public int Id { get; set; }
    public string Name { get; set; }
    public virtual ICollection<Staff> Staffs { get; set; }
}
1
10/19/2019 10:33:08 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow