gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 17:32:54 47 4
gpt4 key购买 nike

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

    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/

47 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com