开发者

How to update a record without selecting that record again in ADO.NET Entity Framework?

开发者 https://www.devze.com 2022-12-31 10:53 出处:网络
Hi all I am doing something like this - void update(ClasstoUpdate obj)//obj is already hav开发者_高级运维ing values to update...

Hi all I am doing something like this -

void update(ClasstoUpdate obj)//obj is already hav开发者_高级运维ing values to update...
{
  var data= (from i in Entityobject.ClasstoUpdate 
            where obj.Id==i.Id
            select i).FirstorDefault();
  data.Name="SomeCoolName";
  EntityObject.SaveChanges();
}

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.

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.

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消