简体   繁体   English

SaveChanges 失败后的 EF Core 修复问题

[英]EF Core Fix issues After SaveChanges Failure

I have this piece of code (in Asp.net core), I try to add a list of objects to DB:我有这段代码(在 Asp.net 内核中),我尝试将对象列表添加到 DB:

try
   {
      await _context.AddRangeAsync(mhUserAtts);
      await _context.SaveChangesAsync();
   }
catch()
   {

   }

When some objects conflict with DB, how can I remove them from the list?当某些对象与 DB 冲突时,如何将它们从列表中删除? And then return to save the rest to DB.然后返回将 rest 保存到 DB。

In addition to suggested answer in comment, If you want the single query to be executed for entry, you can filter already existing records and attempt to add those which are new as following.除了评论中建议的答案外,如果您希望执行单个查询以进行输入,您可以过滤现有记录并尝试添加新的记录,如下所示。

try
   {
      var userAttsInDb =  await _context.UserAtt.Where(u => mhUserAtts.Any(x => x.Id == 
         u.Id)).Select(u => u.Id).ToArrayAsync();
      var mhUserAttsToAdd= mhUserAtts.Where(u => !userAttsInDb.Contains(u.Id));

      await _context.AddRangeAsync(mhUserAttsToAdd);
      await _context.SaveChangesAsync();
   }
catch(){ }

Note: you may need to handle async await properly.注意:您可能需要正确处理异步等待。

Use transactions (if you db supports it)使用事务(如果你的数据库支持它)

public async Task MyDataProcessingAsync(CancellationToken token) {
        using var context = new DbContext();
        using var transaction = await context.Database.BeginTransactionAsync(token);
        try {
            // adding, removing, updating...
            await context.SaveChangesAsync(token);
            await transaction.CommitAsync(token);
        }
        catch {
            // undo all changes
            await transaction.RollbackAsync();
            throw;
        }
    }

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

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