我正在使用Entity Framework来处理数据库,我有自引用模型如下:
public class PhysicalObject
{
public PhysicalObject()
{
SubPhysicalObjects = new HashSet<PhysicalObject>();
}
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
public int? ParentId { get; set; }
[StringLength(150)]
public string Title { get; set; }
public virtual PhysicalObject Parent { get; set; }
public virtual ICollection<PhysicalObject> SubPhysicalObjects { get; set; }
}
我使用 GraphDiff 库来更新断开连接的图表,但它似乎不支持更新自引用图表。
我的问题是:使用Entity Framework更新自引用图的最佳方法是:
删除/更新现有的物理对象
插入不存在的物理对象
答案 0 :(得分:0)
我们说我有两个实体如下:
public class PhysicalObject
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
public int? ParentId { get; set; }
public int StorageRequestId { get; set; }
public string Title { get; set; }
public virtual PhysicalObject Parent { get; set; }
public virtual ICollection<PhysicalObject> SubPhysicalObjects { get; set; }
public virtual StorageRequest StorageRequest { get; set; }
}
public class StorageRequest
{
public StorageRequest()
{
PhysicalObjects = new HashSet<PhysicalObject>();
}
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
public string Title { get; set; }
public virtual ICollection<PhysicalObject> PhysicalObjects { get; set; }
}
请注意,PhysicalObject是自引用表。
不要让我们使用实体框架更新图表:
var oldPhysicalObjects = dbContext.PhysicalObjects.Where(x => x.StorageRequestId== storageRequestId).ToList();
var existingIds = new HashSet<int>();
foreach (var item in newGraphDto.PhysicalObjects.ToList())
{
updateGraph(item, oldPhysicalObjects, dbContext, storageRequestId,existingIds);
}
var posToDelete = oldPhysicalObjects.Where(x => existingIds.All(e => e != x.Id)).ToList();
dbContext.PhysicalObjects.RemoveRange(posToDelete);
dbContext.SaveChanges();
updateGraph方法将以递归方式更新每个PhysicalObjects树,它看起来像:
private void updateGraph(PhysicalObjectDto physicalObjectDto, IList<PhysicalObject> oldPhysicalObjects, MyDbContext dbContext, int storageRequestId, HashSet<int> existingIds, PhysicalObject parent = null)
{
if (physicalObjectAddEditDto.Id == 0)
{
PhysicalObject po = new PhysicalObject
{
Id = physicalObjectAddEditDto.Id,
Title = physicalObjectAddEditDto.Title,
StorageRequestId = storageRequestId,
Parent=parent
};
dbContext.PhysicalObjects.Add(po);
parent = po;
}
else
{
var po = oldPhysicalObjects.FirstOrDefault(x => x.Id == physicalObjectAddEditDto.Id);
po.Title = physicalObjectAddEditDto.Title;
po.StorageRequestId = storageRequestId;
po.Parent = parent;
dbContext.Entry(po).CurrentValues.SetValues(po);
parent = po;
}
existingIds.Add(parent.Id);
foreach (var subPhysicalObject in physicalObjectAddEditDto.SubPhysicalObjects)
{
updateGraph(subPhysicalObject, oldPhysicalObjects, dbContext, mailRoomRequestId, existingIds, parent);
}
}
我希望我的代码能帮助其他人知道如何更新自引用表的图树