gpt4 book ai didi

c# - 更新 Entity Framework 中的嵌套对象

转载 作者:太空狗 更新时间:2023-10-30 01:31:22 24 4
gpt4 key购买 nike

最近我发现 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 层嵌套。

最佳答案

所以我弄清楚了如何才能完成这项工作。在特定的存储库类中,我做了几个 foreach 循环,将 EntityState 设置为已修改。根据我们的业务规则,Project 需要有 Service 和 Position,而 OrganizationUnit for Position 是可选的,所以我检查它是否不为空。这是我的解决方案:

DbContext.Entry(entity).State = EntityState.Modified;
foreach (var service in entity.Service)
{
DbContext.Entry(service).State = EntityState.Modified;
foreach (var position in service.Positions)
{
DbContext.Entry(position).State = EntityState.Modified;
if (position.OrganizationUnit == null) continue;
foreach (var organizationUnit in position.OrganizationUnit)
{
DbContext.Entry(organizationUnit).State = EntityState.Modified;
}
}
}
DbContext.SaveChanges();

现在,当我想在任何级别更新我的对象时,它会在我的数据库中更新。

关于c# - 更新 Entity Framework 中的嵌套对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41739901/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com