用实体框架选择时动态的id数

时间:2012-07-11 18:57:57

标签: entity-framework dynamic parameters numbers

我正在创建一个网站,我需要从ID中选择动态nuber和我使用实体框架,所以我的问题不是这样做

IQueryable source = content.Products;

List<Object> o = new List<Object>();

foreach(int ID in IDS)
 o.Add(content.Where(s => s.id == ID).FirstOrDefault()); // getting the row from DB   foreach loop

而不是这个我希望从动态数量的ID中获取所有来自数据库的实体,如

o = content.Where(s = s.id == ID || s.id == ID || s.ID == ID).ToList();

但where条件需要像字符串一样动态,所以我可以从循环中添加id然后使选择像

string s = "where ";

foreach(int id in ids)
s += " id = " + id + " or ";

o = content.Where(s).ToList;

所以我只访问了一次数据库而不是每次需要多次访问数据库。

1 个答案:

答案 0 :(得分:0)

您可以使用Contains

List<Product> o = content.Where(s => ids.Contains(s.id)).ToList();

它转换为SQL IN子句,并在单个查询中加载具有给定ids的所有产品。