首先,我的控制器中有一个变量来存储linq查询结果,如下所示:
var test= from m in db.testTable
join n in db.testTable2
on m.ID equals n.ID into tabA
from a in tabA
join o in db.testTable3
on m.UserID equals o.ID
select new { .................};
if (test.Count() > 0)
{
foreach (var k in test)
{
ViewData["dropDown_xxx"] = test.Select(j => new { Value = j.ID, Text = j.Description})
.AsEnumerable()
.Select(j => new SelectListItem // Work with in-memory objects using LINQ to Objects instead of LINQ to Entities
{
Value = j.Value.ToString(),
Text = j.Text
}).ToList();
}
以上工作完美,我可以生成下拉列表和ViewData 现在我正在尝试将此linQ查询移动到另一个类而不是放入此控制器,如下所示:
public class testClass{
public IQueryable<dynamic> TestMethod(){
return from m in db.testTable
join n in db.testTable2
on m.ID equals n.ID into tabA
from a in tabA
join o in db.testTable3
on m.UserID equals o.ID
select new { .................};
}
}
现在在我之前的Controller中调用它:
var test= new testClass().TestMethod();
if (test.Count() > 0)
{
foreach (var k in test)
{
ViewData["dropDown_xxx"] = test.Select(j => new { Value = **j.ID**, Text = **j.Description**})
.AsEnumerable()
.Select(j => new SelectListItem // Work with in-memory objects using LINQ to Objects instead of LINQ to Entities
{
Value = j.Value.ToString(),
Text = j.Text
}).ToList();
}
我可以知道代码有什么问题吗?在 J.ID 和 J.Description ,它现在抱怨表达式树可能不包含动态操作
答案 0 :(得分:0)
此处您的动态类型仅在TestMethod
的范围内。您最好创建新类并将该类返回给调用者。
public class testClass{
public IQueryable<MyClass> TestMethod(){
return from m in db.testTable
join n in db.testTable2
on m.ID equals n.ID into tabA
from a in tabA
join o in db.testTable3
on m.UserID equals o.ID
select new MyClass{ .................};
}
}
如果您需要返回匿名类型,请检查此