Optional One to Many relationships in Entity Framework

Last Reply 16 days ago By dharmendr

Posted 18 days ago

Hello every one;

can we have optional one to many relationship in entityframework

 Note: a person can be realate to a department or it might no and a Department can have many 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);

 For Example

Id                     Name                    DepartmentId

1                       John                      x

2                       Ahmad                   y

3                       Persony                NULL

4                       Personz                  x

thanks