简体   繁体   English

Entity Framework Core dbContext 拒绝更改后的行为

[英]Entity Framework Core dbContext behavior after rejecting changes

I have a C# .NET Core API project with Entity Framework.我有一个带有实体框架的 C# .NET Core API 项目。 In one of these APIs, there is a specific case where I need to abort the change I was making in my db context and then save other different data in my database.在其中一个 API 中,有一种特定情况,我需要中止我在数据库上下文中所做的更改,然后将其他不同的数据保存在我的数据库中。

I found and edited the code a little to do this:我找到并编辑了一些代码来做到这一点:

public void RejectChanges()
{
    var ChangeTracker = new Microsoft.EntityFrameworkCore.ChangeTracking.ChangeTracker(_context);
    foreach (var entry in ChangeTracker.Entries())
    {
        switch (entry.State)
        {
            case EntityState.Modified:
            case EntityState.Deleted:
                entry.State = EntityState.Modified; //Revert changes made to deleted entity.
                entry.State = EntityState.Unchanged;
                break;
            case EntityState.Added:
                entry.State = EntityState.Detached;
                break;
        }
    }
}

It seems to work, but I have a very big doubt: if another API is going to save its own data, does this operation affect also its data, rejecting also those changes?它似乎有效,但我有一个很大的疑问:如果另一个 API 要保存自己的数据,这个操作是否也会影响它的数据,是否也会拒绝这些更改? Or, as I wish, does it affect only the API session that called this method?或者,如我所愿,它只影响调用此方法的 API session 吗?

EXAMPLE: API 1 edits some data in the context, then calls the RejectChanges method.示例:API 1 在上下文中编辑一些数据,然后调用RejectChanges方法。 Meanwhile, the API 2 edits other data and it's going to save.同时,API 2 编辑其他数据,准备保存。 Does RejectChanges , called from API 1 reject also the edits made by API 2?从 API 1 调用的RejectChanges是否也拒绝 API 2 所做的编辑?

The Change Tracker is scoped to a single DbContext, which should be scoped to a single API request. Change Tracker 的范围限定为单个 DbContext,它应该限定为单个 API 请求。 Also you don't create a new ChangeTracker.此外,您不会创建新的 ChangeTracker。 The DbContext already has one. DbContext 已经有一个。

var ChangeTracker = _context.ChangeTracker;

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

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