如何做动态Linq

时间:2015-06-02 09:22:41

标签: c# linq entity-framework

我有一个Linq查询,它应该动态地使用多个参数。基于null条件,Where子句字符串应包含/ exclude from Where子句字符串。我使用第三方Dynamic Linq库来实现这一目标。以下是代码,

代码

var boo = (from b in db.Bibs
from inf in db.InfoTypes.Where(info => info.Id == b.InfoTypeId).DefaultIfEmpty()
from it in db.Items.Where(itms => itms.BibId == b.Id).DefaultIfEmpty()
from ic in db.Collections.Where(coll => coll.Id == it.CollectionId).DefaultIfEmpty()
from il in db.ItemLocations.Where(iloc => iloc.Id == it.LocationId).DefaultIfEmpty()
from aacc in db.AdminAccounts.Where(aacc => aacc.Id == b.CreatedBy).DefaultIfEmpty()
from bc in db.BibContents.Where(bc => bc.BibId == b.Id).DefaultIfEmpty()
.Where("inf.Description='E-Working Papers'")
select new Book
{
    BibId = b.Id,
    Type = inf.Description,
    NoOfCopies = db.Items.Where(itms => itms.BibId == b.Id).Count(),
    createdby = db.AdminAccounts.Where(acc => acc.Id == b.CreatedBy).Select(aac => aac.Name).FirstOrDefault(),
    ModifiedBy = db.AdminAccounts.Where(acc => acc.Id == b.LastModifiedBy).Select(aac => aac.Name).FirstOrDefault(),
    createdon = b.CreatedOn,
    lastmodifiedon = b.LastModifiedOn,
    catalogdate = b.CatalogDate
}).GroupBy(g => new { g.BibId }).Select(s => s.FirstOrDefault());

当我运行上面的代码时,我正在

  

LINQ to Entities无法识别方法System.Linq.IQueryable [Vibrant_ClassLibrary.BibContent]其中[BibContent](System.Linq.IQueryable [Vibrant_ClassLibrary.BibContent],System.String,System.Object [])方法,以及此方法无法转换为商店表达式。

1 个答案:

答案 0 :(得分:1)

这与here描述的问题类似。 您必须在.AsEnumerable()电话之前插入.Where(queryString);否则实体框架会尝试转换queryString本身,但它不具备此功能。