如何使用Entity Framework更新来自实体的单个字段? [英] How can I update a single field from an entity with Entity Framework?

查看:89
本文介绍了如何使用Entity Framework更新来自实体的单个字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要从数据库中加载一个对象,修改其某些字段和关系,然后只想为一个字段存储一个新值,而不修改其余部分。

I need to load an object from the database, modify some of its fields and relations, and then I want to store a new value for only one field, without modifying the rest.

它看起来像这样:

var thing = db.Things.First();

thing.Field1 = "asdas";
thing.Field2 = 23;
thing.OtherThings.Add(new OtherThing());
thing.FieldToUpdate = doSomething(thing);

db.SaveChanges();

但这将保存所有更改,我只想保存FieldToUpdate ...

But that would save all the changes, what I want is to only save FieldToUpdate...

我环顾四周,发现使用的是存储过程,对于看起来如此简单的东西来说,这似乎太多了,除了我必须做出不同的选择每次需要执行类似操作时都需要存储过程...

I've looked around and all I've found is to use stored procedures, which seems like too much for something that looks so simple, besides I would have to make a different stored procedure for each time I need to do something like this...

我当前的解决方案是打开另一个上下文,再次加载该东西,更新FieldToUpdate和SaveChanges,

My current solution is to open another context, load the thing again, update the FieldToUpdate and SaveChanges, but that's both inefficient and ugly.

推荐答案

如果要对附加的实体执行此操作,则必须更新FieldToUpdate FIRST并调用SaveChanges 。然后,您可以更新其他字段,并在需要时再次调用SaveChanges。附加实体没有其他方法。

If you want to do this with attached entity you have to update FieldToUpdate FIRST and call SaveChanges. Than you can update other fields and call SaveChanges again if needed. No other way with attached entity.

您可以尝试的另一种方法是分离实体,修改您想要的内容(它不会跟踪更改)。然后将实体附加到上下文并调用:

Other way you can try is to detach entity, modify what you want to (it will not track changes). Then attach entity back to context and call:

// I suppose that db is ObjectContext or inherited type
db.ObjectStateManager.GetObjectStateEntry(thing).SetModifiedProperty("FieldToUpdate");

现在仅跟踪FieldToUpdate的更改。

Now only FieldToUpdate is tracked as changed.

这篇关于如何使用Entity Framework更新来自实体的单个字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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