entity-frameworkentity-framework-6entity.net-4.8ef-fluent-api

Optional One to many Relationship using Entity Framework 6 (Fluent API)


Can we have an optional one to many relationship in Entity Framework 6?

Look at the following classes Department and Person

public class Person
{
    public int Id{ get; set; }
     
    public Department Department { get; set; }
    public int DepartmentId
}
 
public class Department
{
    public int Id{ get; set; }
     
    public List<Person> Members { get; set; }
}

Person to Department
.HasOptional(m => m.Department)
.WithOptional( d => d.Members)
.HasForeignKey( m=> m.DepartmentId);

and the Result should be like this.

Id              Name            DepartmentId

1               John            x
2               Ahmad           y
3               Persony         NULL
4               Personz         x

As you can see from the above example some person has department and some don't and the department have a list of persons.

Now this gives me an error. Like this

Multiplicity conflicts with the referential constraint in Role Because all of the properties in the Dependent Role are non-nullable, multiplicity of the Principal Role must be '1'.


Solution

  • The problem is that your model and configuration does not match. In the fluent API you're configuring the foreign key of the dependent to be optional but in your model the foreign key is required:

    In your Person class change:

    public int DepartmentId
    

    to

    public int? DepartmentId
    

    This way you ensure that the foreign key can actually have the value 'NULL' in the database.