微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

我试图以下列方式执行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();
}

原文地址:https://www.jb51.cc/csharp/92879.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐