在下面的代碼中,我想myEntity使用 EF Core 多次向資料庫添加物件。但每次在屬性 id 上具有不同的值,但所有其他屬性都是相同的。我怎樣才能做到這一點?因為它只在資料庫中添加 1 行。
我想這樣做是因為我不想GetCurrentLocalDateTime在每次迭代以及 else 陳述句中重復呼叫 ()。
var myEntity = _mapper.Map<AEntity >(entityDto);
myEntity.updatedAt = _helper.GetCurrentLocalDateTime();
myEntity.CreatedAt = _helper.GetCurrentLocalDateTime();
if (entityDto.ids != null || entityDto.ids.Count > 0)
{
foreach (var id in entityDto.ids)
{
myEntity.id = id;
await _dbContext.myEntities.AddAsync(myEntity);
}
}
else
{
await _dbContext.myEntities.AddAsync(myEntity);
}
await _dbContext.SaveChangesAsync();
uj5u.com熱心網友回復:
您不能添加一個類的單個實體,更改它的一個屬性,然后再次添加它,期望將一個新實體添加到您的資料庫中。將會發生的只是您更改了已添加的單個實體的屬性。
相反,您需要多次映射 DTO,以便將物體類的多個實體添加到DbSet.
您還需要在您的情況下使用&&而不是。如果集合是,則使用 OR( ) 將導致 a 。||if||NullReferenceExceptionentityDto.idsnull
var now = _helper.GetCurrentLocalDateTime();
if (entityDto.ids != null && entityDto.ids.Count > 0)
{
foreach (var id in entityDto.ids)
{
var myEntity = _mapper.Map<AEntity>(entityDto);
myEntity.updatedAt = now;
myEntity.CreatedAt = now;
myEntity.id = id;
await _dbContext.myEntities.AddAsync(myEntity);
}
}
else
{
var myEntity = _mapper.Map<AEntity>(entityDto);
myEntity.updatedAt = now;
myEntity.CreatedAt = now;
await _dbContext.myEntities.AddAsync(myEntity);
}
await _dbContext.SaveChangesAsync();
uj5u.com熱心網友回復:
它使用它來添加多個資料。看看這些
.AddRangeAsync()
.AddRange()
您可以嘗試將資料保存在串列中并使用“addrange()”一次性保存
uj5u.com熱心網友回復:
是的,這是可能的,但我會小心確保這只是插入多個副本:
foreach (var id in entityDto.ids)
{
myEntity.id = id;
await _dbContext.myEntities.AddAsync(myEntity);
_dbContext.Entry(myEntity).State = EntityState.Detached;
}
通過分離物體,DbContext 將不再跟蹤它,因此更新它并再次添加它將被視為添加新物體的請求。
通常這種代碼會導致開發人員試圖重用單個物體實體來更新多個資料行的錯誤。插入相同資料的多個副本是一個相當奇怪的要求,所以我會確保它被很好地記錄下來,這樣未來的開發人員就不會嘗試重新利用它。:)
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/414968.html
標籤:
上一篇:將管理員用戶播種到資料庫OnModelCreating
下一篇:無法創建物體框架代碼優先遷移
