c# - Entity Framework 错误 : An object with a null EntityKey value cannot be attached to an object context

标签 c# entity-framework entity-framework-4

在我的应用程序中,我有以下代码...

    public Boolean SaveUserInformation(UserInfoDTO UserInformation)
    {
        return dataManager.SaveUserInfo(new UserInfo()
        {
            UserInfoID = UserInformation.UserInfoID.HasValue ? UserInformation.UserInfoID.Value : 0,
            UserID = UserInformation.UserID,
            ProxyUsername = UserInformation.ProxyUsername,
            Email = UserInformation.Email,
            Status = UserInformation.Status
        });
    }

此代码调用一个使用 Entity Framework 的 dataManager 对象的方法...

    public Boolean SaveUserInfo(UserInfo userInfo)
    {
        try
        {
            //Validate data prior to database update
            if (userInfo.UserID == null) { throw new Exception("UserInfoDomainModel object passed to PriorityOne.Data.DataManager.SaveUserInfo with UserID property set to NULL."); }
            if (userInfo.ProxyUsername == null) { throw new Exception("UserInfoDomainModel object passed to PriorityOne.Data.DataManager.SaveUserInfo with ProxyUsername property set to NULL."); }
            if (userInfo.Email == null) { throw new Exception("UserInfoDomainModel object passed to PriorityOne.Data.DataManager.SaveUserInfo with Email property set to NULL."); }

            if (userInfo.UserInfoID == 0)
            {
                //Perform Insert
                using (PriorityOneEntities entities = new PriorityOneEntities())
                {
                    entities.UserInfoes.AddObject(userInfo);
                    entities.SaveChanges();
                }
            }
            else
            {
                //Perform Update
                using (PriorityOneEntities entities = new PriorityOneEntities())
                {
                    entities.Attach(userInfo);
                    entities.SaveChanges();
                }
            }

            return true;
        }
        catch (Exception ex)
        {
            //TODO: Log Error
            return false;
        }

    }

这段代码中的插入工作得很好。但是,当我尝试执行更新时,我收到一条错误消息:“无法将具有空 EntityKey 值的对象附加到对象上下文。”

它出现在这行代码中:entities.Attach(userInfo);

我想要完成的是避免为了选择我稍后要更改和更新的记录而往返于数据库,从而往返于数据库两次。

有什么想法出了什么问题,或者我如何才能更好地完成它?

谢谢。

最佳答案

看来您使用的是 EF 4.1+
您必须告诉 EF 您希望更新您的实体(已修改状态):

//Perform Update
using (PriorityOneEntities entities = new PriorityOneEntities())
{
    entities.Entry(userInfo).State = EntityState.Modified;
    entities.SaveChanges();
}

附言您不必显式调用 Attach。它是在幕后完成的。

更新:
根据您的评论,您使用的是 EF 4.0。要附加在 EF 4.0 中修改的对象,您必须执行以下操作:

 ctx.AddObject("userInfoes", userInfo);
 ctx.ObjectStateManager.ChangeObjectState(userInfo, EntityState.Modified);
 ctx.SaveChanges();  

您不能使用Attach 方法。来自 http://msdn.microsoft.com/en-us/library/bb896271.aspx :

If more than one entity of a particular type has the same key value, the Entity Framework will throw an exception. To avoid getting the exception, use the AddObject method to attach the detached objects and then change the state appropriately.

关于c# - Entity Framework 错误 : An object with a null EntityKey value cannot be attached to an object context,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8496943/

相关文章:

asp.net-mvc - Azure 数据库出现错误:参数 'nameOrConnectionString' 不能为 null、为空或仅包含空格

c# - 使用 Entity Framework 的 SQL 查询运行速度较慢,使用了错误的查询计划

c# - Entity Framework 代码一级关系

MySQL 和 Entity Framework - 调用存储过程的应用程序返回 0 行受影响但相同的过程在终端中工作

entity-framework-4 - Entity Framework 4 - 自定义复杂类型映射

c# - 在字符串中的连续数字后面插入字符串?

c# - GridView列宽调整

c# - Asp.net HttpCookie 指定端口

c# - async 和 await 不起作用

sql-server - Entity Framework 4 与 LINQ to SQL,适用于中小型应用程序,与 SQL Server 配合使用