我对LINQ查询和EF都不太熟悉,通常我使用MySQL,不知道如何编写非常简单的查询。
我想选择表中的所有结果。因此,我使用了以下代码:
ZXContainer db = new ZXContainer();
ViewBag.ZXproperties = db.ZXproperties.All();
但我发现我需要在All(---)里写些东西。
有人可以指导我如何做吗?如果有任何好的参考链接,也请告诉我,非常感谢。
我对LINQ查询和EF都不太熟悉,通常我使用MySQL,不知道如何编写非常简单的查询。
我想选择表中的所有结果。因此,我使用了以下代码:
ZXContainer db = new ZXContainer();
ViewBag.ZXproperties = db.ZXproperties.All();
但我发现我需要在All(---)里写些东西。
有人可以指导我如何做吗?如果有任何好的参考链接,也请告诉我,非常感谢。
bool isTrue = db.ZXproperties.All(z => z.SomeFieldName == true);
ViewBag.ZXproperties = db.ZXproperties.ToList();
ViewBag.ZXproperties = from s in db.ZXproperties
select s;
ViewBag.ZXproperties = db.ZXproperties;
.ToList()
的优点是,如果您想要对此ViewBag.ZXproperties进行多次调用,它只需要在分配变量时进行初始数据库调用。但是,如果对数据执行任何可查询操作,例如.Where()
,则会执行另一个查询,如果您已经拥有数据,则这不是理想情况。如果要选择所有内容,只需跳过.All(...)
,因为ZXproperties已经是一个集合。
ZXContainer db = new ZXContainer();
ViewBag.ZXproperties = db.ZXproperties;
在使用此集合之前,您可能希望(或有时甚至需要)调用.ToList()
...
你不需要使用 All。只需输入即可。
ViewBag.ZXproperties = db.ZXproperties;
或者
ViewBag.ZXproperties = db.ZXproperties.ToList();
var result = db.ZXproperties.ToList();
欲了解更多有关 linq 的信息,请参见 101 linq sample
。
一切都是对所有项及其参数的检查,称为 lambda 表达式
。
All 方法用于确定集合中的所有项是否都满足某个条件。
如果您只想获取所有项,可以直接使用它:
ViewBag.ZXproperties = db.ZXproperties;
ViewBag.ZXproperties = db.ZXproperties.ToList();
这将强制立即通过网络传输。