如何使用实体框架仅更新一个字段?
-
30-09-2019 - |
题
这是表格
用户
UserId
UserName
Password
EmailAddress
和代码..
public void ChangePassword(int userId, string password){
//code to update the password..
}
解决方案
Ladislav的答案已更新以使用DBContext(在EF 4.1中引入):
public void ChangePassword(int userId, string password)
{
var user = new User() { Id = userId, Password = password };
using (var db = new MyEfContextName())
{
db.Users.Attach(user);
db.Entry(user).Property(x => x.Password).IsModified = true;
db.SaveChanges();
}
}
其他提示
您可以告诉EF哪些属性必须以这种方式更新:
public void ChangePassword(int userId, string password)
{
var user = new User { Id = userId, Password = password };
using (var context = new ObjectContext(ConnectionString))
{
var users = context.CreateObjectSet<User>();
users.Attach(user);
context.ObjectStateManager.GetObjectStateEntry(user)
.SetModifiedProperty("Password");
context.SaveChanges();
}
}
您基本上有两个选择:
- 一直走 EF 路,在这种情况下,你会
- 根据加载对象
userId
提供 - 整个对象被加载 - 更新
password
场地 - 使用上下文保存对象
.SaveChanges()
方法
- 根据加载对象
在这种情况下,具体如何处理就看 EF 了。我刚刚对此进行了测试,如果我只更改对象的单个字段,EF 创建的内容几乎也是您手动创建的内容 - 类似于:
`UPDATE dbo.Users SET Password = @Password WHERE UserId = @UserId`
因此 EF 足够智能,可以找出哪些列确实发生了更改,并且它将创建一个 T-SQL 语句来处理那些实际上需要的更新。
- 您在 T-SQL 代码中定义了一个完全符合您需要的存储过程(只需更新
Password
给定的列UserId
没有别的 - 基本上执行UPDATE dbo.Users SET Password = @Password WHERE UserId = @UserId
),然后在 EF 模型中为该存储过程创建一个函数导入,然后调用此函数,而不是执行上述步骤
我正在使用这个:
实体:
public class Thing
{
[Key]
public int Id { get; set; }
public string Info { get; set; }
public string OtherStuff { get; set; }
}
dbContext:
public class MyDataContext : DbContext
{
public DbSet<Thing > Things { get; set; }
}
登录代码:
MyDataContext ctx = new MyDataContext();
// FIRST create a blank object
Thing thing = ctx.Things.Create();
// SECOND set the ID
thing.Id = id;
// THIRD attach the thing (id is not marked as modified)
db.Things.Attach(thing);
// FOURTH set the fields you want updated.
thing.OtherStuff = "only want this field updated.";
// FIFTH save that thing
db.SaveChanges();
在寻找解决此问题的解决方案时,我发现了Goneale的答案有所不同 帕特里克·德斯贾丁斯(Patrick Desjardins)的博客:
public int Update(T entity, Expression<Func<T, object>>[] properties)
{
DatabaseContext.Entry(entity).State = EntityState.Unchanged;
foreach (var property in properties)
{
var propertyName = ExpressionHelper.GetExpressionText(property);
DatabaseContext.Entry(entity).Property(propertyName).IsModified = true;
}
return DatabaseContext.SaveChangesWithoutValidation();
}
"如您所见,它以其第二个参数为函数的表达式。这将通过在lambda表达式中指定要更新的属性来使用此方法。"
...Update(Model, d=>d.Name);
//or
...Update(Model, d=>d.Name, d=>d.SecondProperty, d=>d.AndSoOn);
(这里也给出了一些类似的解决方案: https://stackoverflow.com/a/5749469/2115384 )
我目前正在使用自己的代码中使用的方法, ,扩展到处理类型的(LINQ)表达式 ExpressionType.Convert
. 以我为例,这是必要的 Guid
和其他对象属性。这些被“包裹”在convert()中,因此没有由 System.Web.Mvc.ExpressionHelper.GetExpressionText
.
public int Update(T entity, Expression<Func<T, object>>[] properties)
{
DbEntityEntry<T> entry = dataContext.Entry(entity);
entry.State = EntityState.Unchanged;
foreach (var property in properties)
{
string propertyName = "";
Expression bodyExpression = property.Body;
if (bodyExpression.NodeType == ExpressionType.Convert && bodyExpression is UnaryExpression)
{
Expression operand = ((UnaryExpression)property.Body).Operand;
propertyName = ((MemberExpression)operand).Member.Name;
}
else
{
propertyName = System.Web.Mvc.ExpressionHelper.GetExpressionText(property);
}
entry.Property(propertyName).IsModified = true;
}
dataContext.Configuration.ValidateOnSaveEnabled = false;
return dataContext.SaveChanges();
}
在实体框架核心中, Attach
返回条目,因此您需要的只是:
var user = new User { Id = userId, Password = password };
db.Users.Attach(user).Property(x => x.Password).IsModified = true;
db.SaveChanges();
我在这里迟到了游戏,但这就是我的做法,我花了一段时间来寻找与我满意的解决方案。这会产生一个 UPDATE
仅针对更改的字段进行声明,因为您明确地通过“白色列表”概念定义了它们是什么,该概念更安全,以防止Web表单注入。
我的Isession数据存储库的摘录:
public bool Update<T>(T item, params string[] changedPropertyNames) where T
: class, new()
{
_context.Set<T>().Attach(item);
foreach (var propertyName in changedPropertyNames)
{
// If we can't find the property, this line wil throw an exception,
//which is good as we want to know about it
_context.Entry(item).Property(propertyName).IsModified = true;
}
return true;
}
如果您愿意的话,可以将其包裹在尝试中。
它会以这种方式来称呼(对我来说,这是通过ASP.NET Web API):
if (!session.Update(franchiseViewModel.Franchise, new[]
{
"Name",
"StartDate"
}))
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.NotFound));
我知道这是一个旧线程,但我也在寻找类似的解决方案,并决定使用 @doku-so的解决方案。我要评论要回答@imran Rizvi问的问题,我遵循了 @doku-so链接,该链接显示了类似的实现。 @Imran Rizvi的问题是,他使用提供的解决方案“无法将lambda表达式转换为type'expression> []',因为它不是委托类型'。我想为 @doku-so的解决方案提供一个小的修改,以解决此错误,以防其他人遇到此帖子并决定使用 @doku-so的解决方案。
问题是更新方法中的第二个参数,
public int Update(T entity, Expression<Func<T, object>>[] properties).
使用提供的语法来调用此方法...
Update(Model, d=>d.Name, d=>d.SecondProperty, d=>d.AndSoOn);
您必须在第二个灌食处添加“参数”关键字。
public int Update(T entity, params Expression<Func<T, object>>[] properties)
或者,如果您不想更改方法签名,请调用更新方法,您需要添加'新的'关键字,指定数组的大小,然后最终将每个属性的集合对象初始化器语法使用如下所示更新。
Update(Model, new Expression<Func<T, object>>[3] { d=>d.Name }, { d=>d.SecondProperty }, { d=>d.AndSoOn });
在 @doku-so的示例中,他指定了表达式数组,因此您必须传递属性以在数组中进行更新,因为数组您还必须指定数组的大小。为了避免这种情况,您还可以更改表达式参数以使用iEnumerable而不是数组。
这是我对 @doku-so解决方案的实现。
public int Update<TEntity>(LcmsEntities dataContext, DbEntityEntry<TEntity> entityEntry, params Expression<Func<TEntity, object>>[] properties)
where TEntity: class
{
entityEntry.State = System.Data.Entity.EntityState.Unchanged;
properties.ToList()
.ForEach((property) =>
{
var propertyName = string.Empty;
var bodyExpression = property.Body;
if (bodyExpression.NodeType == ExpressionType.Convert
&& bodyExpression is UnaryExpression)
{
Expression operand = ((UnaryExpression)property.Body).Operand;
propertyName = ((MemberExpression)operand).Member.Name;
}
else
{
propertyName = System.Web.Mvc.ExpressionHelper.GetExpressionText(property);
}
entityEntry.Property(propertyName).IsModified = true;
});
dataContext.Configuration.ValidateOnSaveEnabled = false;
return dataContext.SaveChanges();
}
用法:
this.Update<Contact>(context, context.Entry(modifiedContact), c => c.Active, c => c.ContactTypeId);
@doku-so使用通用的方法提供了一种很酷的方法,我使用了该概念来解决我的问题,但是您只是无法按照 @doku-so的解决方案和链接的帖子,没有人回答使用错误问题。
实体框架跟踪您通过DBContext从数据库查询的对象上的更改。例如,如果您dbcontext实例名称为dbcontext
public void ChangePassword(int userId, string password){
var user = dbContext.Users.FirstOrDefault(u=>u.UserId == userId);
user.password = password;
dbContext.SaveChanges();
}
在EntityFramework Core 2.x中无需 Attach
:
// get a tracked entity
var entity = context.User.Find(userId);
entity.someProp = someValue;
// other property changes might come here
context.SaveChanges();
在SQL Server中尝试了此操作并对其进行了分析:
exec sp_executesql N'SET NOCOUNT ON;
UPDATE [User] SET [someProp] = @p0
WHERE [UserId] = @p1;
SELECT @@ROWCOUNT;
',N'@p1 int,@p0 bit',@p1=1223424,@p0=1
查找确保已经加载的实体不会触发选择,并在需要时自动附加实体(来自文档):
/// Finds an entity with the given primary key values. If an entity with the given primary key values
/// is being tracked by the context, then it is returned immediately without making a request to the
/// database. Otherwise, a query is made to the database for an entity with the given primary key values
/// and this entity, if found, is attached to the context and returned. If no entity is found, then
/// null is returned.
我用 ValueInjecter
Nuget使用以下方式将绑定模型注入数据库实体:
public async Task<IHttpActionResult> Add(CustomBindingModel model)
{
var entity= await db.MyEntities.FindAsync(model.Id);
if (entity== null) return NotFound();
entity.InjectFrom<NoNullsInjection>(model);
await db.SaveChangesAsync();
return Ok();
}
请注意,如果它们从服务器中无效,则可以使用自定义约定的使用情况。
ValueInjecter V3+
public class NoNullsInjection : LoopInjection
{
protected override void SetValue(object source, object target, PropertyInfo sp, PropertyInfo tp)
{
if (sp.GetValue(source) == null) return;
base.SetValue(source, target, sp, tp);
}
}
用法:
target.InjectFrom<NoNullsInjection>(source);
值注射器V2
抬头 这个答案
警告
您将不知道该物业是否有意清除为null,或者只是没有任何价值。换句话说,属性值只能用另一个值替换,但不能清除。
我在寻找同样的地方,最后我找到了解决方案
using (CString conn = new CString())
{
USER user = conn.USERs.Find(CMN.CurrentUser.ID);
user.PASSWORD = txtPass.Text;
conn.SaveChanges();
}
相信我,它像魅力一样对我有用。
结合了几个建议,我提出以下建议:
async Task<bool> UpdateDbEntryAsync<T>(T entity, params Expression<Func<T, object>>[] properties) where T : class
{
try
{
var entry = db.Entry(entity);
db.Set<T>().Attach(entity);
foreach (var property in properties)
entry.Property(property).IsModified = true;
await db.SaveChangesAsync();
return true;
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine("UpdateDbEntryAsync exception: " + ex.Message);
return false;
}
}
被称为
UpdateDbEntryAsync(dbc, d => d.Property1);//, d => d.Property2, d => d.Property3, etc. etc.);
或者
await UpdateDbEntryAsync(dbc, d => d.Property1);
或者
bool b = UpdateDbEntryAsync(dbc, d => d.Property1).Result;
public async Task<bool> UpdateDbEntryAsync(TEntity entity, params Expression<Func<TEntity, object>>[] properties)
{
try
{
this.Context.Set<TEntity>().Attach(entity);
EntityEntry<TEntity> entry = this.Context.Entry(entity);
entry.State = EntityState.Modified;
foreach (var property in properties)
entry.Property(property).IsModified = true;
await this.Context.SaveChangesAsync();
return true;
}
catch (Exception ex)
{
throw ex;
}
}
public void ChangePassword(int userId, string password)
{
var user = new User{ Id = userId, Password = password };
using (var db = new DbContextName())
{
db.Entry(user).State = EntityState.Added;
db.SaveChanges();
}
}