首先更新实体框架代码中的记录的单个属性 [英] Update a single property of a record in Entity Framework Code First

查看:62
本文介绍了首先更新实体框架代码中的记录的单个属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在不先检索记录的情况下更新记录的单个属性? 我问的是 EF Code First 4.1

How can I update a single property of a record without retrieving it first? I'm asking in the context of EF Code First 4.1

说我有一个User类,映射到Database中的表Users:

Says I have a class User, mapping to table Users in Database:

class User
{
    public int Id {get;set;}
    [Required]
    public string Name {get;set;}
    public DateTime LastActivity {get;set;}
    ...
}

现在,我想更新用户的LastActivity.我有用户名.通过查询用户记录,将新值设置为LastActivity,然后调用SaveChanges(),我可以轻松地做到这一点.但这会导致多余的查询.

Now I want to update LastActivity of a user. I have user id. I can easily do so by querying the user record, set new value to LastActivity, then call SaveChanges(). But this would result in a redundant query.

我通过使用Attach方法来解决.但是由于EF如果Name为null则会在Name上引发验证异常,因此我将Name设置为随机字符串(不会更新回DB).但这似乎不是一个很好的解决方案:

I work around by using Attach method. But because EF throws a validation exception on Name if it's null, I set Name to a random string (will not be updated back to DB). But this doesn't seem a elegant solution:

using (var entities = new MyEntities())
{
    User u = new User {Id = id, Name="this wont be updated" };
    entities.Users.Attach(u);
    u.LastActivity = DateTime.Now;
    entities.SaveChanges();
}

如果有人可以为我提供更好的解决方案,我将非常感激.并请原谅我没有任何错误,因为这是我第一次提出关于SO的问题.

I would be very appriciate if someone can provide me a better solution. And forgive me for any mistake as this is the first time I've asked a question on SO.

推荐答案

这是验证实现的问题.验证只能验证整个实体.它不会仅验证修改后的属性,如预期的那样.因此,在要使用不完整的虚拟对象的情况下,应关闭验证:

This is a problem of validation implementation. The validation is able to validate only a whole entity. It doesn't validate only modified properties as expected. Because of that the validation should be turned off in scenarios where you want to use incomplete dummy objects:

using (var entities = new MyEntities())
{
    entities.Configuration.ValidateOnSaveEnabled = false;

    User u = new User {Id = id, LastActivity = DateTime.Now };
    entities.Users.Attach(u);
    entities.Entry(user).Property(u => u.LastActivity).IsModified = true;
    entities.SaveChanges();
}

如果要使用相同的上下文来更新虚拟对象和用于更新应使用验证的整个实体,那么这显然是一个问题.验证发生在SaveChanges中,因此您不能说应该验证哪些对象,而不能验证.

This is obviously a problem if you want to use the same context for update of dummy objects and for update of whole entities where the validation should be used. The validation take place in SaveChanges so you can't say which objects should be validated and which don't.

这篇关于首先更新实体框架代码中的记录的单个属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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