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?
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 usedNullable<int>
type (?
is a shortcut forNullable<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; }
}