如何更新记录而不在 ADO.NET Entity Framework 中再次选择该记录?

How to update a record without selecting that record again in ADO.NET Entity Framework?(如何更新记录而不在 ADO.NET Entity Framework 中再次选择该记录?)
本文介绍了如何更新记录而不在 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 中再次选择该记录?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

DispatcherQueue null when trying to update Ui property in ViewModel(尝试更新ViewModel中的Ui属性时DispatcherQueue为空)
Drawing over all windows on multiple monitors(在多个监视器上绘制所有窗口)
Programmatically show the desktop(以编程方式显示桌面)
c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
LINQ many-to-many relationship, how to write a correct WHERE clause?(LINQ多对多关系,如何写一个正确的WHERE子句?)