EF4代码优先:如何更新只有特定的领域 [英] EF4 Code First: how to update specific fields only

查看:93
本文介绍了EF4代码优先:如何更新只有特定的领域的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在实体更新仅某些领域



我有一个用户实体,像这样:

 公共类用户
{
公共字符串userid {搞定;组; }
公共字符串PasswordHash {搞定;组; }
公共BOOL IsDisabled {搞定;组; }
公众的DateTime AccessExpiryDate {搞定;组; }
公共BOOL MustChangePassword {搞定;组; }
公众的DateTime dateCreated会获得{;组; }
公众的DateTime LastActivity {搞定;组; }
}



所以,如果举例来说,我想更新用户的实体,但做不想更改用户密码,我该怎么办



目前,我用下面的代码更新的实体:

 使用(VAR _cnt =新STQContext())
{
_cnt.Entry<项目>(项目)= .STATE System.Data这.EntityState.Modified;
_cnt.SaveChanges();
的回报;
}


解决方案

试试这个:

 使用(VAR _cnt =新STQContext())
{
_cnt.Users.Attach(用户);
_cnt.Entry<使用者>(用户).Property(U => u.PasswordHash).IsModified = TRUE;
_cnt.SaveChanges();
}


How do I update only certain fields on an entity?

I have a User entity like so:

public class User
{
    public string UserId { get; set; }
    public string PasswordHash { get; set; }
    public bool IsDisabled { get; set; }
    public DateTime AccessExpiryDate { get; set; }
    public bool MustChangePassword { get; set; }
    public DateTime DateCreated { get; set; }
    public DateTime LastActivity { get; set; }
}

So if for example, I want to update the user entity, but do not want to change the user password, how do I do that?

Currently, I'm using the following code to update entities:

using (var _cnt = new STQContext())
{
   _cnt.Entry<Item>(item).State = System.Data.EntityState.Modified;
   _cnt.SaveChanges();
   return;
}

解决方案

Try this:

using (var _cnt = new STQContext())
{
   _cnt.Users.Attach(user);
   _cnt.Entry<User>(user).Property(u => u.PasswordHash).IsModified = true;
   _cnt.SaveChanges();
}

这篇关于EF4代码优先:如何更新只有特定的领域的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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