【发布时间】:2017-01-19 10:48:27
【问题描述】:
最近我发现 EF 不更新嵌套对象。 几天来,我试图弄清楚如何做到这一点,但不幸的是我遇到了这个问题。
我有对象
public class ProjectEntity : AuditableEntity<int>
{
public string CustumerCompany { get; set; }
public string CustomerRepresentative { get; set; }
public string ProjectTitle { get; set; }
public string WwsNumber { get; set; }
[ForeignKey("ParentProjectId")]
public virtual ProjectEntity ParentProject { get; set; }
public int? ParentProjectId { get; set; }
public virtual ICollection<ProjectServicesEntity> Service { get; set; }
}
然后是服务对象
public class ProjectServicesEntity : AuditableEntity<int>
{
/// <summary>
/// Service Number
/// </summary>
public int Number { get; set; }
/// <summary>
/// Service Name
/// </summary>
public string Name { get; set; }
/// <summary>
/// Positions
/// </summary>
public virtual ICollection<ProjectPositionsEntity> Positions { get; set; }
[ForeignKey("ProjectId")]
public virtual ProjectEntity Project { get; set; }
public int ProjectId { get; set; }
}
和位置对象:
public class ProjectPositionsEntity : AuditableEntity<int>
{
/// <summary>
/// Position number
/// </summary>
public int Number { get; set; }
/// <summary>
/// Position Name
/// </summary>
public string Name { get; set; }
/// <summary>
/// Organization Unit for position
/// </summary>
public virtual ICollection<ProjectsOutsourcedPositionEntity> OrganizationUnit { get; set; }
/// <summary>
/// Represents if position is outsourced
/// </summary>
public bool OutSource { get; set; }
/// <summary>
/// Comments for position
/// </summary>
public string Remarks { get; set; }
[ForeignKey("ServiceId")]
public virtual ProjectServicesEntity Service { get; set; }
public int ServiceId { get; set; }
}}
还有我的更新方法:
public void Update(T entity)
{
DbContext.Entry(entity).State = EntityState.Modified;
DbContext.SaveChanges();
}
当页面显示所有数据时,当我尝试在服务或位置中编辑某些数据时,它不会更新。 有人遇到过这种问题吗?
我看到的每个示例都只是嵌套对象的深度为 1 级,但正如您所见,我的对象有 2 级嵌套。
【问题讨论】:
-
您确定更改是从您的页面到达服务器的吗?如果您在测试工具(控制台应用程序)中尝试此操作,它的行为是否相同?例如,编写一个小型控制台应用程序,加载一些数据并更改对象,然后保存它。保存有效吗?
-
我猜你说的是断开连接的对象。 EF 从来没有解决过这个问题,你可以看看GraphDiff 包。
-
@AdamBenson 是的,我确定。问题是 EF 仅更新标记为已修改的 EF 对象,并且此状态不适用于子对象。所以我需要为他们设置修改。我发布了我的解决方案
标签: c# .net entity-framework entity-framework-6