Search code examples
entity-framework-core

virtual property will not update to null


I am working with 2 entities: Hospital Facility The hospital has a one-to one relationship with facility that is nullable. I added public virtual Facility Facility to the Hospital entity and did a migration:

public class Hospital
{
    public virtual Facility Facility { get; set; }
}

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

All looks good in the database. A nullable FacilityId foreign key has been added to the Hospital table. I can set that value to null directly through MMSM. However, when I try and do this through code, it will not update/set to null. Here's my last attempt:

if (facilityId != null)
{
    hospital.Facility = _dbContext.Facility.Find(facilityId);
} 
else
{
    hospital.Facility = null;
}

_dbContext.Hospital.Update(hospital);

So odd, has anyone ran into this issue?


Solution

  • If the relationship is optional then make the navigation property and any FK null-able:

    public class Hospital
    {
        public virtual Facility? Facility { get; set; }
    }
    

    Your code example did not include a call to SaveChanges() so nothing would be persisted in that case.

    The next important step when updating an existing Hospital, ensure any existing Facility is eager loaded. Avoid using Update and detached entities when working with related entity graphs. Fetch the entity and transfer values across. Simpler and safer.

    var hospital = _dbContext.Hospitals
        .Include(h => h.Facility)
        .Single(h => h.HospitalId == hospitalId);
    
    if (facilityId != null)
        hospital.Facility = _dbContext.Facility.Find(facilityId);
    else
        hospital.Facility = null;
    
    _dbContext.SaveChanges();
    

    If you are updating an existing hospital that had a facility ID set and you want to clear it because an updated facility reference was removed then EF needs to know that there "was" a facility associated with the hospital and you intend to remove it by setting it to #null. If you fetch a hospital without eager loading the existing facility then the property is already #null so the change tracker doesn't pick up on anything to update. Calls to Update() could result in a #null being written but it is generally better to avoid Update() as it can lead to data overwrites you don't intend.