简体   繁体   English

如何强制执行实体框架以保存更改?

[英]How to enforce entity framework to save changes?

I have the following method:我有以下方法:

public async Task<Unit> Handle(Command request, CancellationToken cancellationToken)
        {
            var accounts = await _context.Accounts.ToListAsync();

            var currentAccountIndex = accounts.FindIndex(x => x.Id == request.Id);

            var currentAccount = accounts[currentAccountIndex];

            var previousAccount = accounts[currentAccountIndex - 1];

            accounts[currentAccountIndex] = previousAccount;

            accounts[currentAccountIndex - 1] = currentAccount;

            bool changesDetected = _context.ChangeTracker.HasChanges();

            await _context.SaveChangesAsync();

            return Unit.Value;
        }

I save in memory a list of accounts from the database using EF, then I swap two elements in that list and want to apply the changes back to the database.我使用 EF 在内存中保存了数据库中的帐户列表,然后我交换了该列表中的两个元素,并希望将更改应用回数据库。 What you see above is the happy path, no error or out of bounds checking.你在上面看到的是快乐的路径,没有错误或越界检查。

However entity framework seems to believe that no changes occured as changesDetected is false .然而,实体框架似乎认为没有发生任何变化,因为changesDetectedfalse Is there a way to explicitly tell EF that there are some changes that I want to be saved ?有没有办法明确告诉 EF我想要保存一些更改?

What would change in the database, when you store the list back?当您将列表存储回去时,数据库会发生什么变化? Has any of the elements of the list, any of the "entities" really changed?列表中的任何元素、任何“实体”真的发生了变化吗? Would any data in any row in the database change?数据库中任何行中的任何数据都会改变吗?

Think about it: How was the order of elements determined in first place when you ToList'ed them?想一想:当您对元素进行 ToList 时,元素的顺序是如何首先确定的?

If you analyze that problem properly, you will notice that what you tried to do has no sense.如果你正确地分析了那个问题,你会发现你试图做的事情毫无意义。

If you want to control the order of the items, then you have to control it , not believe that something does it.如果你想控制项目的顺序,那么你必须控制它,而不是相信某事会发生。 Define sorting criteria to get predictable ordering.定义排序标准以获得可预测的排序。 Then, when you want to permanently change the order of the items, modify the underlying data (the data the criteria check during sorting), and that's it.然后,当您想要永久更改项目的顺序时,修改基础数据(标准在排序期间检查的数据),仅此而已。

According your code, there are nothing change on the Entity.根据您的代码,实体没有任何变化。 If you want to force EF to update database, you can call Update method, force EF to update everything of the entity even there are no changes.如果你想强制 EF 更新数据库,你可以调用Update方法,强制 EF 更新实体的所有内容,即使没有更改。 the sample code as below:示例代码如下:

public async Task<Unit> Handle(Command request, CancellationToken cancellationToken)
        {
            ....
            _context.Accounts.Update(currentAccount);
            _context.Accounts.Update(previousAccount);
            // now the changesDetected will be true
            bool changesDetected = _context.ChangeTracker.HasChanges();
      
            await _context.SaveChangesAsync();
            ....
        }

You can make sure the EF saves the changes by attaching the modified entities and marking them as modified as shown in the code below:您可以通过附加修改后的实体并将它们标记为已修改来确保 EF 保存更改,如下面的代码所示:

public async Task<Unit> Handle(Command request, CancellationToken cancellationToken)
{
    var accounts = await _context.Accounts.ToListAsync();
    var currentAccountIndex = accounts.FindIndex(x => x.Id == request.Id);
    var currentAccount = accounts[currentAccountIndex];
    var previousAccount = accounts[currentAccountIndex - 1];

    accounts[currentAccountIndex] = previousAccount;
    accounts[currentAccountIndex - 1] = currentAccount;

    // attach the modified entities to the context
    _context.Accounts.Attach(previousAccount);
    _context.Accounts.Attach(currentAccount);

    // mark the modified entities as modified
    _context.Entry(previousAccount).State = EntityState.Modified;
    _context.Entry(currentAccount).State = EntityState.Modified;

    await _context.SaveChangesAsync();

    return Unit.Value;
}

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

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