简体   繁体   English

EF Core 更新现有实体

[英]EF Core update an existing entity

I'm using EF Core and .NET 6 and I would like to essentially upsert an entity to a table - a fairly simple ask.我正在使用 EF Core 和 .NET 6,我想基本上将实体插入到表中 - 一个相当简单的问题。

I have the following code:我有以下代码:

var countries = GetCountries();

using (var scope = scopeFactory.CreateScope())
{
    var dbContext = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>();

    foreach (var c in countries)
    {
        // check if the country already exists.
        var exists = dbContext.Countries.Where(d => d.Id == c.Id).FirstOrDefault();

        // if already exists - update (rather than add).
        if (exists != null) 
        {
            exists.Name = c.Name;
            exists.DisplayName = c.DisplayName;
            ... // omitted other prop updates.

            dbContext.Countries.Update(exists);
        } 
        else
        {
            dbContext.Countries.Add(c);
        }
    }

    await dbContext.SaveChangesAsync();
}

I was wondering - is there was a more efficient way to update without manually looking up then updating (it's not very performant).我想知道 - 是否有一种更有效的方式来更新,而无需手动查找然后更新(它的性能不是很好)。

Preferably, I was hoping there was a Merge method in EF Core but can't find anything useful (that's free...).最好,我希望 EF Core 中有一个Merge方法,但找不到任何有用的东西(那是免费的......)。 Rather than doing the manual lookup and update in this way.而不是以这种方式进行手动查找和更新。

I'm probably missing something very obvious here - thanks for any pointers in advance!我可能在这里遗漏了一些非常明显的东西-提前感谢您的任何指示!

EF Core do not have Merge , or similar for Upsert. EF Core 没有Merge或 Upsert 的类似功能。 You can improve performance of your query by selecting existng items in one batch.您可以通过选择一批中的现有项目来提高查询的性能。 Also you do not need to call Update , just change properties.此外,您不需要调用Update ,只需更改属性。

var countries = GetCountries();

using (var scope = scopeFactory.CreateScope())
{
    var dbContext = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>();

    var countyIds = countries.Select(c => c.Id);
    var existing = (await dbContext.Countries.Where(d => countyIds.Contains(d.Id))
        .ToListAsync())
        .ToDictionary(c => c.Id);

    foreach (var c in countries)
    {
        // check if the country already exists.

        if (existing.TryGetValue(c.Id, out var toUpdate))
        {
            // if already exists - update (rather than add).
            toUpdate.Name = c.Name;
            toUpdate.DisplayName = c.DisplayName;
            ... // omitted other prop updates.
        } 
        else
        {
            dbContext.Countries.Add(c);
        }
    }

    await dbContext.SaveChangesAsync();
}
public void InsertOrUpdate(Entity entity) 
{ 
    using (var context = new dbContext.Countries()) 
    { 
        context.Entry(entity).State = entity.Id == 0 ? 
                                   EntityState.Added : 
                                   EntityState.Modified; 

        context.SaveChanges(); 
    } 
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM