消除 LINQ 查询之间的冗余
我需要多次调用相同的 LINQ 查询,这些查询仅在“where”子句中具有不同的元素。我不想一遍又一遍地重复 LINQ 查询,而是想将元素传递到单个查询中,但我对如何执行此操作感到困惑。
现在,我的基本 LINQ 查询如下所示:
return from a in _repository.GetApps()
join set in _repository.GetSettings() on a.id equals set.application_id
join type in _repository.GetSettingsTypes() on set.setting_type_id equals type.id
join ent in _repository.GetEntities() on a.entity_id equals ent.id
where ent.ROW_ID == app && set.application_id == id && (set.setting_type_id==81 || set.setting_type_id==82 || set.setting_type_id==83)
orderby set.application_id, type.ordinal
select new Settings { app_name = a.name, data_type = type.data_type, setting_name = type.name, setting_description = type.description, setting_value = set.setting_value, entity_name = ent.name, entity_num = ent.ROW_ID };
“where”子句仅按 ID 列出设置类型。其他调用将简单地用更多或更少的设置 ID 替换“where”子句,然后返回到视图。如何动态替换“where”子句或设置 ID?我可以简单地将字符串或数组分配给第二个“&&”后面的设置列表吗(这似乎不起作用)?或者 Lambda 会在这里提供帮助吗(我也无法让它发挥作用)?谢谢!
I need to call identical LINQ queries multiple times that only have differing elements in the "where" clause. Instead of repeating the LINQ query over and over again, I'd like to pass the elements into a single query instead, but I'm brain stuttering on how to do that.
Right now my base LINQ query looks like this:
return from a in _repository.GetApps()
join set in _repository.GetSettings() on a.id equals set.application_id
join type in _repository.GetSettingsTypes() on set.setting_type_id equals type.id
join ent in _repository.GetEntities() on a.entity_id equals ent.id
where ent.ROW_ID == app && set.application_id == id && (set.setting_type_id==81 || set.setting_type_id==82 || set.setting_type_id==83)
orderby set.application_id, type.ordinal
select new Settings { app_name = a.name, data_type = type.data_type, setting_name = type.name, setting_description = type.description, setting_value = set.setting_value, entity_name = ent.name, entity_num = ent.ROW_ID };
The "where" clause just lists setting types by IDs. The other calls will simply replace that "where" clause with more or fewer setting ids which then get returned to a view. How can I dynamically replace that "where" clause or the setting ids? Can I simply assign a string or array to the setting list following the second "&&" (this didn't seem to work)? Or would Lambdas help here (I also couldn't get that to work)? Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以将数组与
Contains()
查询结合使用:You can use an array combined with a
Contains()
query:必须使用查询语法吗?您可以使用 LINQ 扩展方法并将不同的 lambda 表达式传递到Where 方法中吗?
Do you have to use Query syntax? Can you use LINQ extension methods and pass different lambda expressions into the Where method?