简体   繁体   English

更新对象上下文时发生EF 6错误

[英]EF 6 error occurred while updating the object context

I have Entity 我有实体

public class User : BaseEntity, IEntity
{
    public string UserName { get; set; }

    public string Avatar { get; set; }

    [IgnoreMap]
    public string Password { get; set; }

    public int RoleId { get; set; }

    public virtual Role Role { get; set; }

    public string RoleName { get; set; }

    public int RangId { get; set; }

    public string RangName { get; set; }

    public string Email { get; set; }

    public string LastName { get; set; }

    public string FirstName { get; set; }

    public string SurName { get; set; }

    public DateTime? Birthday { get; set; }

    public int Gender { get; set; }

    public int? CountryId { get; set; }

    public virtual Country Country { get; set; }

    public int? CityId { get; set; }

    public virtual City City { get; set; }

    public string Skype { get; set; }

    public string WebSite { get; set; }

    public string Interest { get; set; }

    public string Signature { get; set; }

    public DateTime DateRegistered { get; set; }

    public string IpAddress { get; set; }

    public string PasswordChange { get; set; }

    public Guid? ActivateKey { get; set; }

    public DateTime? DatePasswordChange { get; set; }

    public int TotalPost { get; set; }

    public string NewEmail { get; set; }

I try update role of user 我尝试更新用户的角色

var user = this._userRepository.GetEntity(userId);
user.RoleId = role.Id;

I try set navigation property to null 我尝试将导航属性设置为null

user.Role = null;

I try set navigation property to new role 我尝试将导航属性设置为新角色

user.Role = role;

But I always get error 但是我总是会出错

Additional information: The changes to the database were committed successfully, but an error occurred while updating the object context. 附加信息:对数据库的更改已成功提交,但是更新对象上下文时发生错误。 The ObjectContext might be in an inconsistent state. ObjectContext可能处于不一致状态。 Inner exception message: A referential integrity constraint violation occurred: The property value(s) of 'Role.Id' on one end of a relationship do not match the property value(s) of 'User.RoleId' on the other end. 内部异常消息:违反了参照完整性约束:关系一端的“ Role.Id”的属性值与另一端的“ User.RoleId”的属性值不匹配。

For save date I'm using 为了保存日期,我正在使用

this._context.Entry(entity).State = EntityState.Modified;

UPDATE: 更新:

I found interesting fact. 我发现了一个有趣的事实。 Sometimes I can change user role, and sometimes I can't. 有时我可以更改用户角色,有时不能。 Examples 例子

When user activation his account, I can change user role. 当用户激活他的帐户时,我可以更改用户角色。

When user change email, I can't change user role. 用户更改电子邮件时,我无法更改用户角色。

I using code almost the same 我使用的代码几乎相同

Update 更新

Code for activation user work fine 激活用户的代码工作正常

    public bool ActivateUser(Guid key)
    {
        var user = this._userRepository.GetEntity(item => item.ActivateKey == key);
        var role = this._roleRepository.GetEntity(item => item.RoleType == RoleType.User);

        if (user != null)
        {
            user.ActivateKey = null;
            user.RoleId = role.Id;
            this._userRepository.UpdateEntity(user);
            this._userRepository.SaveChanges();

            return true;
        }

        return false;
    }

Code for edit email user, I get error 用于编辑电子邮件用户的代码,出现错误

A referential integrity constraint violation occurred: The property value(s) of 'Role.Id' on one end of a relationship do not match the property value(s) of 'User.RoleId' on the other end. 发生引用完整性约束冲突:关系一端的“ Role.Id”的属性值与另一端的“ User.RoleId”的属性值不匹配。

    public void UpdateEmail(int userId, string newEmail, string browserAgent, string ip)
    {
        var user = this._userRepository.GetEntity(item => item.Id == userId);
        var role = this._roleRepository.GetEntity(item => item.RoleType == RoleType.NoActivation);
        var activateKey = Guid.NewGuid();

        var editEmailNotification = new EditEmailNotification
        {
            UserName = string.IsNullOrEmpty(user.FirstName) ? user.UserName : user.FirstName,
            OldEmail = user.Email,
            NewEmail = newEmail,
            Ip = ip,
            WebBrowseAgent = browserAgent,
            ActivateKey = activateKey
        };

        user.NewEmail = newEmail;
        user.ActivateKey = activateKey;
        user.RoleId = role.Id;
        this._userRepository.UpdateEntity(user);
        this._userRepository.SaveChanges();

        this.SendNotificationLetterChangedAccountEmail(editEmailNotification);
    }

I had the same problem, and spent 6 hours on it till I found the cause. 我遇到了同样的问题,花了6个小时才找到原因。

I was adding an entity to the context, and then saving. 我在上下文中添加了一个实体,然后保存。 I was keeping the context, and keeping a reference to the entity. 我保持上下文,并保持对实体的引用。 Later when the user pressed 'save' again then the error was caused by adding this same entity again to the same context. 稍后,当用户再次按下“保存”时,错误是由于将该相同实体再次添加到相同上下文而引起的。 Prior to the first save, the state of the entity was 'Added', after first save it was 'Unchanged' - all as expected. 第一次保存之前,实体的状态为“已添加”,第一次保存后为“未更改”-均与预期相同。 When adding the entity the second time its state in the context was then 'Added' and this caused the error. 当第二次添加实体时,其在上下文中的状态被“添加”,这导致了错误。 I had assumed that by adding an existing entity to an existing context, it would keep the state as 'unchanged' (or modified if I modified the entity). 我假设通过将现有实体添加到现有上下文中,它将使状态保持“不变”(如果我修改了实体,则将其修改)。

It seems that the database recognized the added entity as being the same as an existing unchanged one, and so the changes were all saved, but the object context was confused with two states of the same entity, and threw the exception 似乎数据库识别出添加的实体与现有的不变实体相同,因此所有更改都被保存,但是对象上下文与同一实体的两个状态混淆,并引发了异常

The bug was fixed easily by checking the state and only adding if the state is 'detached'. 通过检查状态并仅在状态为“分离”时才添加漏洞,可以轻松修复该错误。 I recognize that the problem may be a symptom of keeping the context for too long, but all this is in one web form. 我认识到问题可能是上下文保持太长时间的症状,但是所有这些都以一种Web形式出现。

Check your navigation properties. 检查您的导航属性。 Most likely that error means that you are updating a navigation property of an entity from one side of a relationship but don't update an entity from another side. 该错误最有可能意味着您正在从关系的一侧更新实体的导航属性,而不是从另一侧更新实体。

Let's take a quick look at the example: 让我们快速看一下示例:

Let's say you have a User which has an ICollection<Roles> that represents it's roles. 假设您有一个User ,该UserICollection<Roles>代表其角色。 And you have a Role which has a User property that refers to user. 并且您具有一个Role ,该Role具有引用用户的User属性。 So if you will try to update the User 's Role list without updating the User inside an appropriate role it will throw you a referential integrity constraint violation error. 因此,如果您尝试更新UserRole列表而不更新相应角色内的User ,则会抛出参照完整性约束违规错误。

Also, please check these links, they might help you in solving your problem: 另外,请检查以下链接,它们可能会帮助您解决问题:

error occurred while updating the object context 更新对象上下文时发生错误

Error:A referential integrity constraint violation occurred on db.SaveChanges() in .net? 错误:.net中的db.SaveChanges()发生参照完整性约束冲突?

How to update entity? 如何更新实体?

Why become referential constraints inconsistent after updating foreign key? 为什么更新外键后引用约束变得不一致?

I found how fix this. 我找到了解决方法。

I updated my method update date. 我更新了方法更新日期。 I added call method this._context.ChangeTracker.DetectChanges(); 我添加了调用方法this._context.ChangeTracker.DetectChanges();

    public void UpdateEntity(T entity, bool isDetectChange = false)
    {
        if (isDetectChange)
        {

            this._context.ChangeTracker.DetectChanges();
        }

        this._context.Entry(entity).State = EntityState.Modified;
    }

We can call method all time or we can in context setting set 我们可以一直调用方法,也可以在上下文设置中调用

 this.Configuration.AutoDetectChangesEnabled = true;

But it's bad idea for performance 但这对性能不好

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

相关问题 更新对象上下文时发生错误 - error occurred while updating the object context 当我尝试将SaveChanges()转换为上下文时,EF中的“更新条目时发生错误” - “An error occurred while updating the entries” in EF when I try to SaveChanges() to context 实体框架:更新条目时出错 - Entity Framework: An error occurred while updating the entries SaveChanges()时更新条目时发生错误 - An error occurred while updating the entries when SaveChanges() 将项目插入上下文EF时出错 - Error while insert items to context EF (400)错误的请求,并且在更新条目时发生错误 - (400) Bad Request and An error occurred while updating the entries “...更新对象上下文时发生错误。 ObjectContext可能处于不一致状态......“ - “… an error occured while updating the object context. The ObjectContext might be in an inconsistent state…” 添加行然后使用EF更新行时出错 - Error while adding a row and then updating a row using EF 准备命令定义时发生错误。 有关详细信息,请参见内部异常 - An error occurred while preparing the command definition. See the inner exception for details EF 在EF 6.2.0中建立与SQL Server的连接时发生与网络相关或特定于实例的错误 - A network-related or instance-specific error occurred while establishing a connection to SQL Server in EF 6.2.0
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM