在实体框架中将LINQ动态查询转换为IQueryable

时间:2015-09-05 00:21:31

标签: c# linq entity-framework-4

我正在尝试转换在实体框架中将两个表连接到IQueryable类型的LINQ查询,以便我可以在其上进一步应用过滤器表达式。

以下是代码:

IQueryable<Bill_Joined_V1> bills = 
     (from primary in _billEntity.BillTable
      join secondary in _billEntity.BillInfoTable on primary.BillID equals secondary.BillID
      orderby primary.BillID
      select new
                {
                    primary.BillID,
                    primary.CustomerID,
                    secondary.Name,
                    secondary.Value
                }).AsQueryable<Bill_Joined_V1>().Where(FilterExp);

实体类如下:

public class Bill_V1
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public Guid BillID { get; set; }

    public string BillTypeID { get; set; }
    public Guid CustomerID { get; set; }
    public Guid UserID { get; set; }

    [ForeignKey("UserID")]
    public virtual User_V1 UserTable { get; set; }

    public double AmountDue { get; set; }
}

public class BillInfo_V1
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public long BillInfoID { get; set; }

    public Guid BillID { get; set; }

    [ForeignKey("BillID")]
    public virtual Bill_V1 BillTable { get; set; }

    public string Name { get; set; }
    public string Value { get; set; }
}

// Dummy bill record for query purpose
public class Bill_Joined_V1
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public long BillRecID { get; set; }

    public Guid BillID { get; set; }
    [ForeignKey("BillID")]
    public virtual Bill_V1 BillTable { get; set; }

    public Guid CustomerID { get; set; }
    [ForeignKey("CustomerID")]
    public virtual Customer_V1 CustomerTable { get; set; }

    public string Name { get; set; }
    public string Value { get; set; }

}

代码无法编译。它会产生错误信息

  

'System.Linq.IQueryable'不包含'AsQueryable'的定义,并且最好的扩展方法重载'System.Linq.Queryable.AsQueryable(System.Collections.Generic.IEnumerable)'有一些无效的参数

有没有办法将LINQ查询转换为IQueryable类型而不将查询结果放到物理表中?我该如何解决这个问题?感谢。

1 个答案:

答案 0 :(得分:-1)

您不需要致电.AsQueryable().Where()旨在返回适当类型的IQueryable。但是代码中IQueryable的确切类型不会是IQueryable<Bill_Joined_V1>,因为您使用的是匿名类型。你真正需要做的是 not 在这里使用匿名类型:

select new
                                {
                                    primary.BillID,
                                    primary.CustomerID,
                                    secondary.Name,
                                    secondary.Value
                                }).

相反,做

select new Bill_Joined_V1 { /* initialize properties */ }