boindiil boindiil - 1 year ago 127
C# Question

Entity Framework set navigation property to null

I have a entity framework database first project. here is a extraction of the model:

public partial class LedProject
public LedProject()
this.References = new HashSet<LedProjectReference>();
this.Results = new HashSet<LedProjectResult>();
this.History = new HashSet<LedProjectHistory>();

public string Identifier { get; set; }
public string Name { get; set; }
public Nullable<System.DateTime> CompletionDate { get; set; }
public System.DateTime CreationDate { get; set; }
public System.Guid ProjectId { get; set; }
public string Comment { get; set; }

public virtual User ContactUser { get; set; }
public virtual User CreationUser { get; set; }
public virtual Customer Customer { get; set; }
public virtual LedProjectAccounting Accounting { get; set; }
public virtual LedProjectState State { get; set; }
public virtual ICollection<LedProjectReference> References { get; set; }
public virtual ICollection<LedProjectResult> Results { get; set; }
public virtual User ResponsibleUser { get; set; }
public virtual ICollection<LedProjectHistory> History { get; set; }

public partial class User
public System.Guid UserId { get; set; }
public string LoginName { get; set; }
public System.DateTime CreationDate { get; set; }
public string Firstname { get; set; }
public string Lastname { get; set; }
public string Email { get; set; }

I have a problem with setting the navigation item ResponsibleUser of the class LedProject. When I set the ResponsibleUser to a another user and afterwards save the changes of the DBContext, the changes are stored in the database.

But, when I want to delete the current ResponsibleUser of an LedProject, by setting the navigation property to null. The changes are not stored in the database.

LedProject project = db.LedProject.Find(projectId);
project.Name = string.IsNullOrEmpty(name) ? null : name;
project.ResponsibleUser = responsibleUser == null ? null : db.User.Find(responsibleUser.UserId);

Is there any trick for deleting navigation properties?

Answer Source

The problem lies in the lazy loading of the navigation property. It seems that the value is first set to null and afterwards loaded from the database. So the desired value (null in my case) is overridden by the currently stored value in the database.

LedProject project = db.LedProject
    .Where(p => p.ProjectId == projectId)

This loads the ResponsibleUser when the Project is loaded. This finally solved my issue!