请教.net mvc 中linq如何实现这个功能?

最近参考网上代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Linq;

namespace WMVC.Models
{
public class RepositoryTest<T> where T : class
{

public DataContext context;
public RepositoryTest(DataContext context)
{
this.context = context;
}
public IEnumerable<T> FindAll(Func<T, bool> exp)
{
return context.GetTable<T>().Where(exp);
}
}
}

 

可以实现: 

DataContext content = new MyDataContext();
RepositoryTest rp
= new RepositoryTest<my_tbl>(DataContext);
rp.FindAll(t
=> t.name == "jack"));
return View(rp);

 

 

 

那么下面我想实现: 

DataContext content = new MyDataContext();
RepositoryTest rp
= new RepositoryTest<my_tbl>(DataContext);
rp.FindAll(
1,t => t.name == "jack")); //这里多加了一个条件
return View(rp);

 

我修改了代码如下,但是无法编译,请教各位前辈应该如何修改,谢谢!

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Linq;

namespace WMVC.Models
{
public class RepositoryTest<T> where T : class
{

public DataContext context;
public RepositoryTest(DataContext context)
{
this.context = context;
}
public IEnumerable<my_tbl> FindAll(int pid, Func<my_tbl, bool> exp)
{
var result
= from a in context.GetTable<my_tbl>()
where a.parent_id == pid
select a;

//result.Where(t=>t.name == "jack"); 可通过
//result.Where(exp); 出错
return result;
}
}
}

 

实际方法定义代码如下:

public IEnumerable<MenuClasses> listBom(int? id,Func<MenuClasses, bool> exp)
{
id
= id == null ? 0 : id;
SourceClassDataContext s
= (SourceClassDataContext)context;
var result
= from a in s.GetTable<tbl_SourceClasses>()
join b
in s.class_f_Cid(id) on
a.id equals b.id into prods
from b
in prods
orderby b.temp_orderby
select
new MenuClasses()
{
id
= a.id,
parent_id
= a.parent_id,
class_order
= a.class_order,
class_name
= a.class_name,
temp_orderby
= b.temp_orderby,
Level
= b.Level

};
//result = result.Where(b => b.Level == 1); //可通过
//result = result.Where<MenuClasses>(exp); //无法通过
return result;
}

 

holdtom
浏览 464回答 1
1回答
打开App,查看更多内容
随时随地看视频慕课网APP