我有以下方法,它接收從 dto 映射的物體。因此,它還沒有被跟蹤。
public async Task UpdateAsync(Entity value, CancellationToken cancellationToken)
{
dbContext.Update(value);
await dbContext.SaveChangesAsync(cancellationToken);
}
public class Entity
{
public Guid Id { get; set; }
public ICollection<Item> Items { get; set; }
}
public class Item
{
public Guid Id { get; set; }
public Guid EntityId { get; set; }
}
物體有一個屬性 Items,它是一對多關系。更新物體并洗掉現有關系或添加新關系的最佳方法是什么?目前它不會洗掉現有的專案,這些專案不再是集合的一部分。我想這是因為并非所有專案都被跟蹤,因為物體是從 dto 創建的。看來我必須先從資料庫加載現有物體和所有關系,然后手動映射所有屬性和關系(添加、洗掉)。這意味著很多作業。有沒有更好的方法來實作這一目標?EF 可以以某種方式洗掉未跟蹤的關系嗎?
uj5u.com熱心網友回復:
不,實際上您需要分離添加/更新或洗掉邏輯。這也是以后維護代碼的更好方法。也許您可以嘗試這種方法(_factory 是 IServiceScopeFactory):
public async Task<TModel> UpdateAsync(TModel model)
{
using var scope = _factory.CreateScope();
await using var context = scope.ServiceProvider.GetRequiredService<ApplicationContext>();
var entry = await context.Set<TModel>().FirstAsync(t => t.Id == model.Id); // try other methods
var entryEntry = context.Entry(entry);
entryEntry.CurrentValues.SetValues(model);
await context.SaveChangesAsync();
return entryEntry.Entity;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/465766.html
上一篇:C#相等比較失敗
下一篇:如何管理帶間隔的定時器
