实体框架错误:具有null EntityKey值的对象不能附加到对象上下文中 [英] Entity Framework Error: An object with a null EntityKey value cannot be attached to an object context

查看:108
本文介绍了实体框架错误:具有null EntityKey值的对象不能附加到对象上下文中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

  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
{
//验证数据库更新前的数据
if(userInfo.UserID == null){throw new Exception(UserInfoDomainModel对象传递给PriorityOne.Data.DataManager.SaveUserInfo,UserID属性设置为NULL); }
if(userInfo.ProxyUsername == null){throw new Exception(UserInfoDomainModel对象传递给PriorityOne.Data.DataManager.SaveUserInfo,ProxyUsername属性设置为NULL); }
if(userInfo.Email == null){throw new Exception(UserInfoDomainModel对象传递给PriorityOne.Data.DataManager.SaveUserInfo with Email属性设置为NULL);

if(userInfo.UserInfoID == 0)
{
//执行插入
(PriorityOneEntities entities = new PriorityOneEntities())
{新新200新新新新旗新新新新旗新新旗新新新新旗新新旗新新旗新新旗2001-新新新新新旗新新旗2001-新新新新旗新新旗2001-新新新新新旗新新旗2001-新新新新新旗新新旗2001-新新新新旗新新旗2001-新新新新旗新新旗2001-新
entities.SaveChanges();
}
}
else
{
//使用(PriorityOneEntities entities = new PriorityOneEntities())执行更新

{
entities.Attach(userInfo);
entities.SaveChanges();新评新新新旗新新新新旗新新旗新新旗旗哨旗新新旗新新旗新新旗新新旗新旗新
}
catch(Exception ex)
{
// TODO:Log Error
return false;
}

}

精细。但是当我尝试执行更新时,我得到一个错误:一个null EntityKey值的对象不能附加到对象上下文。



它发生在这行代码:entities.Attach(userInfo);



我想要完成的是避免做一个往返数据库只是为了选择记录以后我会更改和更新,从而进行两次往返数据库。



任何想法出了什么问题,或者我能如何更好地完成这个? / p>

谢谢。

解决方案

EF 4.1+

您必须告诉EF您希望您的实体进行更新(修改状态):

  //使用(PriorityOneEntities entities = new PriorityOneEntities())执行更新

{
entities.Entry(userInfo).State = EntityState.Modified;
entities.SaveChanges();
}

X-45454545 CEEC X-这是在引擎盖下完成的。



更新

根据您的意见,您使用的是EF 4.0。以下是您在EF 4.0中修改对象的操作:

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

您不能使用附加方法。从 http://msdn.microsoft.com/en-us/library/bb896271。 aspx


如果特定类型的多个实体具有相同的键值,则实体框架将抛出​​异常。为避免获得异常,请使用 AddObject 方法附加分离的对象,然后适当更改状态。



In my application I have the following code...

    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
        });
    }

This code calls a method on a dataManager object that utilizes Entity Framework...

    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;
        }

    }

The insert on this code works just fine. But when I try to perform an update I'm getting an error saying: "An object with a null EntityKey value cannot be attached to an object context."

It occurs on this line of code: entities.Attach(userInfo);

What I'm trying to accomplish is to avoid making a round trip to the database just to select the record that I will later make changes to and update, thus making two round trips to the database.

Any ideas what is going wrong, or how I could better accomplish this?

Thanks.

解决方案

Seems like you're using EF 4.1+
You have to tell EF that you want your entity to be updated (Modified state):

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

P.S. You don't have to explicitly call Attach. It's done under the hood.

Update:
based on your comments, you're using EF 4.0. Here's what you have to do to attach your object as modified in EF 4.0:

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

You cannot use Attach method. From 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.

这篇关于实体框架错误:具有null EntityKey值的对象不能附加到对象上下文中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆