首页 新闻 赞助 找找看

Linq to sql 另一种动态?

0
[已解决问题] 解决于 2016-04-19 12:47
public IList<TEntity> Entities<TEntity>(Func<TEntity, bool> predicate)
            where TEntity : class
{
  var lamda = new Func<DbContext, IQueryable<TEntity>>(db =>
  {
  var iQueryable = from p in db.Set<TEntity>()
            where predicate(p)
            select p;
  Command = iQueryable.ToString();
  return iQueryable;
  });
  return _DBO.Entities(lamda);
}

运行后报错:LINQ to Entities 不支持 LINQ 表达式节点类型“Invoke”。

如果 predicate(p) 写成:
where p.name == "name" && p.id == 123
是 OK 的。

请教各位大神,这里 where 后的表达式如何改成参数传递进去


Me_Code的主页 Me_Code | 初学一级 | 园豆:52
提问于:2016-04-19 11:53
< >
分享
最佳答案
0

看了半天,终于看出你这写法... 无语了...

现在问题来了,你是里面不懂得写还是外面不懂得写。

里面不懂得写是这样写的

var q= db.set<TEntity>().where(predicate)

 

外面这个predicate你懂得怎么写就行了,如果不懂的写,请自行Google网上的predicateBuilder范例。

奖励园豆:5
爱编程的大叔 | 高人七级 |园豆:30839 | 2016-04-19 12:06
    public class DBO<TContext> where TContext : DbContext, new()
    {
        private TContext _Context;

        public IList<TEntity> Entities<TEntity>(Func<TContext, IQueryable<TEntity>> lamda)
            where TEntity : class
        {
            using (_Context = new TContext())
            {                
                var iQueryable = lamda(_Context);
                var iList = iQueryable.ToList();
                return iList;
            }
        }
    }

我想问的是

from p in db.Set<TEntity>()  

where p.name == "name" && p.id == 123

select p;

如何把上述 Linq 中的 where 后的代码作为“参数”传递进去。

如果,直接使用委托 Func 是会报错的。

Me_Code | 园豆:52 (初学一级) | 2016-04-19 12:29

@Me_Code: 

我让你自己Google,既然你不懂Google,贴几个链接给你,自己看吧

http://stackoverflow.com/questions/877034/linq-predicatebuilder-multiple-ors

http://www.albahari.com/nutshell/predicatebuilder.aspx

http://stackoverflow.com/questions/11490893/how-does-predicatebuilder-work

http://stackoverflow.com/questions/25702926/using-a-string-where-clause-with-predicatebuilder-in-linqpad-for-creating-dynami

http://drc.ideablade.com/xwiki/bin/view/Documentation/predicatebuilder-methods

爱编程的大叔 | 园豆:30839 (高人七级) | 2016-04-19 12:33

predicateBuilder 我知道怎么用。

我只是想换种方式。

Me_Code | 园豆:52 (初学一级) | 2016-04-19 12:33

@爱编程的大叔: 我的思路和出发点错了。谢谢。

Me_Code | 园豆:52 (初学一级) | 2016-04-19 12:46
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册