簡體   English   中英

使用 EF Core 多次添加相同的實體 object

[英]Adding same entity object more than once with EF Core

在下面的代碼中,我想使用 EF Core 將myEntity object 多次添加到數據庫中。 但每次在屬性 id 上具有不同的值,但所有其他屬性都是相同的。 我怎樣才能做到這一點? 因為它只在數據庫中添加 1 行。

我想這樣做是因為我不想在每次迭代以及 else 語句中重復調用GetCurrentLocalDateTime ()。

 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(); 

您不能添加 class 的單個實例,更改其屬性之一,然后再次添加它,期望將新實例添加到您的數據庫中。 將會發生的只是您更改了已添加的單個實例的屬性。

相反,您將需要多次 map DTO,以便將實體 class 的多個實例添加到DbSet

您還需要使用&&而不是|| 在你的if條件下。 如果entityDto.ids集合為null ,則使用 OR ( || ) 將導致NullReferenceException

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(); 

它使用它來添加多個數據。看看這些

.AddRangeAsync() .AddRange()

您可以嘗試將數據保存在列表中並使用“addrange()”一次性保存

是的,這是可能的,但我會小心確保這只是插入多個副本:

            foreach (var id in entityDto.ids)
            {
                myEntity.id = id;
                await _dbContext.myEntities.AddAsync(myEntity);
                _dbContext.Entry(myEntity).State = EntityState.Detached;
            }

通過分離實體,DbContext 將不再跟蹤它,因此更新它並再次添加它將被視為添加新實體的請求。

通常這種代碼會導致開發人員試圖重用單個實體實例來更新多個數據行的錯誤。 插入相同數據的多個副本是一個相當奇怪的要求,所以我會確保它被很好地記錄下來,這樣未來的開發人員就不會嘗試重新利用它。 :)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM