在Entity Framework Core 6 C#中执行SQL批量更新以更新一个属性的方法

huangapple go评论57阅读模式
英文:

How to perform SQL batch updates to update one property in Entity Framework Core 6 C#

问题

以下是您要的翻译:

我有以下代码,用于使用Entity Framework在Azure SQL表中执行更新操作

public class DatabaseRepo
{
    private readonly UserContext _context;
    
    public DatabaseRepo(UserContext userContext)
    {
        _context = userContext;
    }        

    public async Task BatchUpdateUsersAsync(List<User> users)
    {           
        foreach (var user in users)
        {
            var entity = await _context.Users
                                       .FirstOrDefaultAsync(item => item.Id == user.Id);
            entity.StartDate = user.StartDate;

            await _context.SaveChangesAsync();
        }
    }
}

我只想更新所有这些用户的“StartDate”值。是否有更好的批量更新方法?

我正在使用EF Core 6

我尝试了这个:

public async Task BatchUpdateUsersAsync(List<User> users)
{
        foreach (var user in users)
        {                
            var entry = _context.Set<User>().Add(user);
            entry.State = EntityState.Modified;
        }

        await _context.SaveChangesAsync();
}
但这会引发关于其他属性不能为空的错误。
英文:

I have the following code to perform an update in Azure SQL table using Entity Framework

public class DatabaseRepo
{
    private readonly UserContext _context;
    
    public DatabaseRepo(UserContext userContext)
    {
        _context = userContext;
    }        

    public async Task BatchUpdateUsersAsync(List<User> users)
    {           
        foreach (var user in users)
        {
	        var entity = await _context.Users
                                       .FirstOrDefaultAsync(item => item.Id == user.Id);
	        entity.StartDate = user.StartDate;

	        await _context.SaveChangesAsync();
	    }
    }
}

All I want to do update StartDate value of all these users. Is there a better way to do batch update?

I'm using EF Core 6

I tried this:

public async Task BatchUpdateUsersAsync(List<User> users)
{
        foreach (var user in users)
        {                
            var entry = _context.Set<User>().Add(user);
            entry.State = EntityState.Modified;
        }

        await _context.SaveChangesAsync();
}

but this throws an error about some other property can't be null.

答案1

得分: 3

EF Core 7引入了新的批量更新功能,包括更新和删除。
来自Microsoft的信息:ExecuteUpdate和ExecuteDelete

您可以使用以下代码:

var dateTime = DateTime.Now;
_context.Users
       .Where(p => p.IsActive || p.Username == "DoNotUpdateMe")
       .ExecuteUpdate(p => p.SetProperty(x => x.StartDate, x => dateTime));
_context.SaveChanges();
英文:

EF Core 7 introduces new bulk update features, including update and delete.
Info from Microsoft: ExecuteUpdate and ExecuteDelete

You can use the following:

var dateTime = DateTime.Now;
_context.Users
       .Where(p => p.IsActive || p.Username == "DoNotUpdateMe")
       .ExecuteUpdate(p => p.SetProperty(x => x.StartDate, x => dateTime));
      _context.SaveChanges();

答案2

得分: 0

`Attach` 更新仅需要的列,这些列的 `IsModified` 值为 true,代码如下:

public async Task BatchUpdateUsersAsync(List<User> users)
{
    foreach (var user in users)
    {
        _context.Set<User>().Attach(user);
        _OSTContext.Entry(user).Property(x => x.StartDate).IsModified = true; // 仅更新 Startdate 列
    }

    await _context.SaveChangesAsync();
}
这将适用于任何 Entity Framework 版本
英文:

Attach Updates only Required column's those are IsModified =true code will be as follows

   public async Task BatchUpdateUsersAsync(List&lt;User&gt; users)
    {
        foreach (var user in users)
        {
            _context.Set&lt;User&gt;().Attach(user);
            _OSTContext.Entry(user).Property(x =&gt; x.StartDate).IsModified = true; //updates only Startdate Column
        }

        await _context.SaveChangesAsync();
    }

This will be use any Entity Frame work version

答案3

得分: -2

你可以使用Select方法进行批量更新,文档中的性能数值如下所示。

更多信息

public class DatabaseRepo
{
    private readonly UserContext _context;
    
    public DatabaseRepo(UserContext userContext)
    {
        _context = userContext;
    }        

    public async Task BatchUpdateUsersAsync(List<User> users)
    {           
        var entities = users.Select(async (user) => await _context.Users.FirstOrDefaultAsync(item => item.Id == user.Id));
        entities.ExecuteUpdate(p => p.SetProperty(u => u.StartDate, u => DateTime.Now));
        await _context.SaveChangesAsync();
    }
}
英文:

You can use the Select method for batch updates, the performance values ​​in the documentation are shared below.

More Info

public class DatabaseRepo
{
    private readonly UserContext _context;
    
    public DatabaseRepo(UserContext userContext)
    {
        _context = userContext;
    }        

    public async Task BatchUpdateUsersAsync(List&lt;User&gt; users)
    {           
        var entities = users.Select(async (user) =&gt; await _context.Users.FirstOrDefaultAsync(item =&gt; item.Id == user.Id));
        entities.ExecuteUpdate(p =&gt; p.SetProperty(u =&gt; u.StartDate, u =&gt; DateTime.Now));
        await _context.SaveChangesAsync();
    }
}

huangapple
  • 本文由 发表于 2023年7月11日 06:05:23
  • 转载请务必保留本文链接:https://go.coder-hub.com/76657620.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定