gpt4 book ai didi

c# - EntityKey 属性只能在属性的当前值为 null 时设置

转载 作者:太空狗 更新时间:2023-10-29 21:10:11 24 4
gpt4 key购买 nike

我正在尝试以下列方式执行 EF 更新,但继续收到此错误:

只有当属性的当前值为 null 时,才能设置 EntityKey 属性。

        using (hydraEntities db = new hydraEntities())
{
YouUser = db.youusers.Include("address").Include("entity").Include("youusercontacts.contact").Include("youuserlogins").Include("youusernotes.note").Include("youusernotes.youuser.entity").Where( yu => yu.YOUUserId.Equals(YOUUserId)).First();
}

YouUser.entity.FirstName = txtFirstName.Text;
YouUser.entity.LastName = txtLastName.Text;
YouUser.address.AddressLine1 = txtAddressLine1.Text;
YouUser.address.AddressLine2 = txtAddressLine2.Text;
YouUser.address.City = txtCity.Text;
YouUser.address.State = ddlState.SelectedValue;
YouUser.address.Zipcode = txtZipcode.Text;

using (hydraEntities db = new hydraEntities())
{
db.youusers.AddObject(YouUser);
db.ObjectStateManager.ChangeObjectState(YouUser, System.Data.EntityState.Modified);
db.SaveChanges();
}

非常感谢任何有关如何解决此问题并执行上述语句的见解。

最佳答案

在这种情况下不要使用 AddObject。它用于插入新实体,但您正在更新现有实体。使用 Attach 代替:

using (hydraEntities db = new hydraEntities())
{
db.youusers.Attach(YouUser);
db.ObjectStateManager.ChangeObjectState(YouUser, System.Data.EntityState.Modified);
db.SaveChanges();
}

关于c# - EntityKey 属性只能在属性的当前值为 null 时设置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8524176/

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