简体   繁体   English

异常实体已被跟踪

[英]Exception Entity Is Already Being Tracked

I'm getting an error for tracking the sane model but I don't know how else to access the model and save the changes.我在跟踪健全的 model 时遇到错误,但我不知道如何访问 model 并保存更改。 The error reads like this:错误如下所示:

        System.InvalidOperationException: 'The instance of entity type 'UserMetaData' cannot be tracked 
    because another instance with the same key value for {'UserId'} is already being tracked. When attaching
     existing entities, ensure that only one entity instance with a given key value is attached. Consider 
    using 'DbContextOptionsBuilder.EnableSensitiveDataLogging' to see the conflicting key values.'

The code that is crashing my site is this:使我的网站崩溃的代码是这样的:

public IActionResult ConsentForm(string holder)
{
    var id = _httpContextAccessor.HttpContext.Session.GetString("UserId");
    var userId = new Guid(id);
    var userMetaInfo = _elearnContext.UserMetaData.Where(u => u.UserId == userId).SingleOrDefault();


    UserMetaData userMetaData = new UserMetaData
    {
        UserId = userId,
        Consent = userMetaInfo.Consent,
        Location = "",
        CanChangePassword = true
    };
    _elearnContext.UserMetaData.Add(userMetaData);// crashes here 
    _elearnContext.SaveChanges();
    return RedirectToAction("LogOn", "Account");
    // return View("~/Views/Home/ConsentForm.cshtml", ConsentData);
}

I think the problem is that before I call this function I am using the same access in the former function like this:我认为问题在于,在调用此 function 之前,我在前 function 中使用相同的访问权限,如下所示:

public IActionResult RedirectToConsentForm(string controllerName, string actionName)
{

    var Id = _httpContextAccessor.HttpContext.Session.GetString("UserId");
    var UserId = new Guid(Id);
    var UserMetaInfo = _elearnContext.UserMetaData.Where(u => u.UserId == UserId).SingleOrDefault();


    if (UserMetaInfo.Consent == true)
    {
        return RedirectToAction("ConsentForm", "Account");

    }
    else
    {
        return RedirectToAction(controllerName, actionName);
    }

}

If any one has any ideas please let me know.如果有人有任何想法,请告诉我。

Your scenario in this case is actually update the metadata if existed otherwise add a new one.在这种情况下,您的方案实际上是更新元数据(如果存在),否则添加一个新元数据。 It crashes because after querying for the metadata, it's tracked ( AsNoTracking is not used).它崩溃是因为在查询元数据后,它被跟踪(不使用AsNoTracking )。 Then that tracked entity is added to the context and causes the error.然后将该跟踪的实体添加到上下文中并导致错误。 Here's how it should be:应该是这样的:

var userMetaInfo = _elearnContext.UserMetaData.SingleOrDefault(u => u.UserId == userId) ?? new UserMetaData();
if(userMetaInfo.UserId == 0){
  //set the consent only at the time creating a new metadata
  userMetaInfo.Location = someLocation;
  userMetaInfo.CanChangePassword = true;
  //add the new entity to the context (mark it as added)
  _elearnContext.UserMetaData.Add(userMetaInfo);
}
//now set this to update the consent which should be true
//because this code is run only after the user accepted (redirected from another action)
userMetaInfo.Consent = true;

//finally save the changes
_elearnContext.SaveChanges();

Note I'm not sure about what you set for the Location (and when to update it).注意我不确定您为Location设置的内容(以及何时更新它)。 So it depends on your logic.所以这取决于你的逻辑。 But it looks like in the code above the only thing you want to update is the Consent property and it must be true .但看起来在上面的代码中,您唯一要更新的是Consent属性,它必须是true Although we check for the UserId to know if it's being creating a new metadata but I believe that at that time, the metadata may already have been created (somewhere else).尽管我们检查UserId以了解它是否正在创建新的元数据,但我相信那时元数据可能已经创建(在其他地方)。 However it's the general logic we process it in this case (something like adding the entity only if there is no existing data, otherwise update the properties on the fetched and tracked entity).然而,这是我们在这种情况下处理它的一般逻辑(类似于仅在没有现有数据时添加实体,否则更新获取和跟踪实体的属性)。

暂无
暂无

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

相关问题 异常{'Id'}已在ChangePasswordAsync()上被跟踪 - exception {'Id'} is already being tracked on ChangePasswordAsync() 实体框架核心 - 无法跟踪实体类型的实例,因为已在跟踪具有键值的另一个实例 - Entity framework Core - The instance of entity type cannot be tracked because another instance with the key value is already being tracked 如何为实体框架已经跟踪的记录加载相关数据 - How to load related data for a record already being tracked by Entity Framework DbContext 抛出已经跟踪的实体,但没有跟踪实体 - DbContext throw already tracked entity but no entity tracked EF:无法跟踪实体类型X的实例,因为已经跟踪了具有相同密钥的此类型的另一个实例 - EF: The instance of entity type X cannot be tracked because another instance of this type with the same key is already being tracked 实体类型的实例……无法跟踪,因为已经在跟踪具有相同键的此类型的另一个实例 - The instance of entity type … cannot be tracked because another instance of this type with the same key is already being tracked 无法跟踪实体类型“xTestType”的实例,因为已跟踪具有相同键的此类型的另一个实例? - The instance of entity type 'xTestType' cannot be tracked because another instance of this type with the same key is already being tracked? 无法跟踪实体类型“ SalesOrder”的实例,因为已经跟踪了具有相同键的该类型的另一个实例 - The instance of entity type 'SalesOrder' cannot be tracked because another instance of this type with the same key is already being tracked 无法跟踪实体类型“Item”的实例,因为已跟踪另一个具有与 {'Id'} 相同键值的实例 - The instance of entity type 'Item' cannot be tracked because another instance with the same key value for {'Id'} is already being tracked 错误:无法跟踪实体类型“X”的实例,因为已在跟踪另一个具有键值“{ID:3}”的实例 - Error: The instance of entity type 'X' cannot be tracked because another instance with the key value '{ID: 3}' is already being tracked
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM