【发布时间】:2012-06-15 04:53:00
【问题描述】:
我有一些代码可以在循环中更改数据库中某些数据的值。我只是想知道首先过滤数据的最有效方法是什么?我举个例子:-
与类:-
public class myObj
{
int id {get;set;}
string product {get; set;}
string parent{get;set;}
bool received {get;set;}
}
还有 DbContext:-
public class myCont:DbContext
{
public DbSet<myObj> myObjs {get;set;}
}
这样做更好吗:-
int[] list;
/* Populate list with a bunch of id numbers found in myOBjs */
myCont data = new myCont();
myObj ob = data.myObjs.Where(o => o.parent == "number1");
foreach(int i in list)
{
ob.First(o => o.id == i && o.received != true).received = true;
}
或者:-
int[] list;
/* Populate list with a bunch of id numbers found in myOBjs */
myCont data = new myCont();
foreach(int i in list)
{
data.myObjs.First(o => o.parent == "number1" && o.id == i && o.received != true).received = true;
}
还是没有区别?
【问题讨论】:
-
你可以使用sql profile来检查linq生成的命令
-
只有代码遍历IQueryable时才会生成sql查询。 EF 推迟执行,直到需要物化一个对象。
-
小的可读性改进:
ob.First(o => o.id == i && o.received != true).received = true; -
@JohnPolvora 我怀疑它可能会这样工作。
-
没有区别。第一个示例中的
ob是IQueryable,并且在两个代码sn-ps 中每次迭代都会执行一次相同的查询(因此,list.Count()次)。 @Asif 的答案中可能会提高性能(即只有一个数据库查询,然后在内存中进行迭代)(无论出于何种奇怪原因,它现在已被否决并删除)。
标签: c# linq entity-framework