如何调用动态指定不同表名的 Linq-to-Entities (EF4) 查询?
我有一堆表,它们都有一个名为 ResourceID
的字段,该字段是从外部进程填充的。我想遍历每个表并根据主列表验证该 ID。代码很简单,但很重复:
var resList = (from r in dc.ResourceMasterEntities select r.ResourceId).ToList();
var res = (from rs in resList select (int?)rs).ToList();
var stage = (from s in dc.TableOne select s.ResourceId).ToList();
foreach (var invalidResourceID in stage.Except(res).ToList())
{
errList.Add("Bad ID found:" + invalidResourceID );
}
stage = (from s in dc.TableTwo select s.ResourceId).ToList();
foreach (var invalidResourceID in stage.Except(res).ToList())
{
errList.Add("Bad ID found:" + invalidResourceID );
}
// more of the same with different tables
我想创建一个函数,可以在其中传递表的名称(TableOne
、TableTwo
等),而不必编写所有这些重复的代码。这可以用 Linq 来完成吗? (最好不要使用 ExecuteQuery :-))
I have a bunch of tables that all have a field called ResourceID
that are populated from an outside process. I want to go through each table and validate that ID against a master list. The code is simple but gets repetitive:
var resList = (from r in dc.ResourceMasterEntities select r.ResourceId).ToList();
var res = (from rs in resList select (int?)rs).ToList();
var stage = (from s in dc.TableOne select s.ResourceId).ToList();
foreach (var invalidResourceID in stage.Except(res).ToList())
{
errList.Add("Bad ID found:" + invalidResourceID );
}
stage = (from s in dc.TableTwo select s.ResourceId).ToList();
foreach (var invalidResourceID in stage.Except(res).ToList())
{
errList.Add("Bad ID found:" + invalidResourceID );
}
// more of the same with different tables
I would like to create a function where I can pass in the name of the table (TableOne
, TableTwo
, etc) and not have to write all of this repetitive code. Can this be done with Linq? (and preferably not using ExecuteQuery
:-))
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以创建一个采用 IQueryable 作为参数的函数。
该函数如下所示:
您可以选择是否创建 errList 和 res 类级别属性,或者将它们作为参数传递给函数
You can create a function that takes an IQueryable as a parameter.
The function would look like:
You can choose if you make errList and res class level properties or if you pas them as parameters to the function
经过一些修改,我能够让它工作 - 我必须使用内置的动态 linq 来选择我想要的属性。
With some modification I was able to get this to work - I had to use the built in dynamic linq to select the property that I wanted.
您可能需要考虑对未知结果类型使用实体 SQL 和 DbDataRecord。有关某些信息,请参阅 http://archive.msdn.microsoft.com/EFQuerySamples 中的 Entity SQL 示例关于如何使用 Entity SQL 的想法。
You may want to consider using entity SQL and DbDataRecord for unknown result types. See the Entity SQL samples in http://archive.msdn.microsoft.com/EFQuerySamples for some ideas on how to use Entity SQL.