Cannot get relationship to update for navigation properties in entity framework

后端 未结 3 646
梦谈多话
梦谈多话 2020-12-05 21:38

I am currently using EF4.3 and Code First. Creation of my objects works (via my views - just using the auto-generated Create), but when I attempt to edit an object, it does

3条回答
  •  [愿得一人]
    2020-12-05 22:22

    Setting the state to Modified only marks scalar properties as modified, not navigation properties. You have several options:

    • A hack (you won't like it)

      //...
      else
      {
          var manager = project.Manager;
          project.Manager = null;
          context.Entry(project).State = EntityState.Modified;
          // the line before did attach the object to the context
          // with project.Manager == null
          project.Manager = manager;
          // this "fakes" a change of the relationship, EF will detect this
          // and update the relatonship
      }
      
    • Reload the project from the database including (eager loading) the current manager. Then set the properties. Change tracking will detect a change of the manager again and write an UPDATE.

    • Expose a foreign key property for the Manager navigation property in your model:

      public class Project
      {
          public int ProjectID { get; set; }
          [Required]
          public string Name { get; set; }
      
          public int ManagerID { get; set; }
          public virtual User Manager { get; set; }
      }
      

      Now ManagerID is a scalar property and setting the state to Modified will include this property. Moreover you don't need to load the Manager user from the database, you can just assign the ID you get from your view:

      Project project = new Project();
      project.ProjectID = projectViewModel.ProjectID;
      project.Name = projectViewModel.Name;
      project.ManagerID = projectViewModel.ManagerID;
      repository.InsertOrUpdateProject(project);
      repository.Save();
      

提交回复
热议问题