多个相似的 linq 查询
我有一个模型课程,其中有多个多对多关系,例如年龄或时间。
我有这个查询:
string IDs = "1,2,3"
string[] IDList = IDs.Split(',');
return (from x in entities.Course
where x.Ages.Where(val => IDList.Contains(val.ID.ToString())).Count() == IDList.Count()
select x);
并且我需要为时间和其他几个属性设置相同的查询,如:
string IDs = "1,2,3"
string[] IDList = IDs.Split(',');
return (from x in entities.Course
where x.Times.Where(val => IDList.Contains(val.ID.ToString())).Count() == IDList.Count()
select x);
如何使查询更加动态,这样我就没有多个类似的查询?
谢谢
I have a model Course, which has several many to many relationships like Age or Time.
I have this query:
string IDs = "1,2,3"
string[] IDList = IDs.Split(',');
return (from x in entities.Course
where x.Ages.Where(val => IDList.Contains(val.ID.ToString())).Count() == IDList.Count()
select x);
And I need to set the same query for Time and several other properties as in:
string IDs = "1,2,3"
string[] IDList = IDs.Split(',');
return (from x in entities.Course
where x.Times.Where(val => IDList.Contains(val.ID.ToString())).Count() == IDList.Count()
select x);
How can I make the query more dynamic so I don't have multiple similar queries?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以创建一个接受
表达式
(取决于您的数据类型)的方法,并以这种方式运行查询。您需要让您的年龄、时间等实现特定的接口才能正常工作。例如,假设您使用 EF 并且您的模型是使用
DbSet
的 Code First,您可以这样做:You could make a method that accepts an
Expression
(depeneding on your data type) and run the query that way. You'll need to make yourAges
,Time
, etc implement a specific interface for it to work.For example, assuming that you are using EF and your model is Code First using
DbSet
s, you could make this:我会创建返回不同查询结果的方法:
原因是方法封装您的查询逻辑 - 只有
where
子句不同。然后您可以传入任何源。您甚至可以将两个查询过滤器组合为链式方法调用:I'd make methods that return the different query results:
The reason is that the method encapsulates your query logic - only the
where
clause is different. You can then pass in any source. You could even combine the two query filters as a chained method call: