附加更新实体框架 [英] Attach for Update Entity Framework

查看:60
本文介绍了附加更新实体框架的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用带有附件的EF 5.x对表进行更新。该表还有其他必填字段,但它是一个现有行。所以我试图更新而没有任何获取。 userid是表的主键。我正在尝试更新状态。但会引发EntityValidationErrors消息,要求输入密码,这是另一个必填字段,而不是主键。由于这是对现有行的更新,因此为什么需要提供需要更新的字段?

I am trying to do an update for a table using EF 5.x using attach. this table has other fields that are required but its an existing row. so i am trying to update without any fetch. userid is the primary key for the table. i am trying to update the status. but it throws an EntityValidationErrors saying password is required which is another required field but not primary key. since this is a update to existing row why do you need to provide the requried fields for update?

    var webUser = new WebUser() { UserId = webUserId, OnlineStatus = (sbyte)status };
    using (var dbxupdate = new xEntities())
    {
        try
        {
            dbxupdate.WebUsers.Attach(webUser);
dbxupdate.Entry(webUser).State = EntityState.Modified;
            dbxupdate.Entry(webUser).Property(x => x.OnlineStatus).IsModified = true;
            dbxupdate.SaveChanges();
        }
        catch (DbEntityValidationException dbEx)
        {
            foreach (var validationErrors in dbEx.EntityValidationErrors)
            {
                foreach (var validationError in validationErrors.ValidationErrors)
                {
                    Trace.TraceInformation("Property: {0} Error: {1}", validationError.PropertyName, validationError.ErrorMessage);
                }
            }
        }
    }


推荐答案

在实体框架中,如果不为其他字段设置适当的值就无法更新字段。因此最好为您的工作使用存储过程。另一种方法是获取记录,然后更新字段。

In entity framework, You can't update a field without setting appropriate values for other fields. so it is better to use a stored procedure for your job. And the other way is to fetch the record and then update the field.

这篇关于附加更新实体框架的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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