如何更新记录而不在 ADO.NET Entity Framework 中再次选择该记录? [英] How to update a record without selecting that record again in ADO.NET Entity Framework?

查看:27
本文介绍了如何更新记录而不在 ADO.NET Entity Framework 中再次选择该记录?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,我正在做这样的事情 -

Hi all I am doing something like this -

void update(ClasstoUpdate obj)//obj is already having values to update...
{
  var data= (from i in Entityobject.ClasstoUpdate 
            where obj.Id==i.Id
            select i).FirstorDefault();
  data.Name="SomeCoolName";
  EntityObject.SaveChanges();
}

我想在不使用 ID 再次查询的情况下执行更新,有什么方法可以将更新的对象传递给 ADO.NET 实体框架并更新它.如果我在这里遗漏了什么,我很抱歉,但这是我一直在做的方式想知道是否有一种简单的更新方法.谢谢.

I want to perform an update without again querying using the Id,is there any way I just pass the updated object to ADO.NET Entity framework and it updates it.I am sorry if I am missing something here but this is the way i have been doing it wondering if there is a simple way to update. Thanks.

推荐答案

更新对象的简单方法是获取它,更改它,然后提交更改,这就是您已经在做的事情.

The simple way to update an object is fetch it, change it, and submit changes which is what you're already doing.

另一种方法是附加对象,并告诉实体对象处于修改状态的框架.

Another way is to attach the object, and tell the entity framework that the object is in a modified state.

第三种方法是通过构造一个直接在数据库中更新对象而不获取它的 SQL 字符串来更新对象.但是我不建议这样做.

A third way is to update the object by constructing an SQL string that updates the object directly in the database without fetching it. However I wouldn't recommend doing this.

附注:记得在你的函数中检查 null.如果您知道 FirstOrDefault 的返回值永远不会为 null,那么您应该使用 First 代替.您可能还想考虑使用 Single 而不是 First.

A side note: remember to check for null in your function. If you know the return value of FirstOrDefault will never be null then you should use First instead. You might also want to consider using Single instead of First.

这篇关于如何更新记录而不在 ADO.NET Entity Framework 中再次选择该记录?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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