从已编译的查询委托中返回匿名类型

时间:2011-12-29 21:49:22

标签: c# sql-server entity-framework c#-4.0 linq-to-entities

我想从编译的查询中返回一个匿名类型,它从两个表中选择多个列。

我尝试使用:

public static Func < DBEntities, string> 

但无法编译它。我尝试创建一个新的数据类型 BOMWorkOrder ,但无法使其工作。可能是我缺少一些语法。

public static Func<DBEntities, string, IQueryable<BOMWorkOrder>> compiledWorkorderQuery =
        CompiledQuery.Compile((DBEntities ctx, string bomNumber) =>
            from items in ctx.BM10200 
            from orders in ctx.BM10300
            where orders.Parent_Component_ID == -1 &&
                    orders.ITEMNMBR == bomNumber &&
                    orders.TRX_ID == items.TRX_ID
            select new 
            {  bomWorkOrder =
                items.TRXDATE,
                orders.TRX_ID,
                orders.ITEMNMBR,
                orders.Assemble_Quantity
            });

工单将是:

public class BOMWorkOrder
{
    public DateTime TransactionDate { get; set; }
    public string TransactionId { get; set; }
    public string ItemNumber { get; set; }
    public int AssemblyQuantity { get; set; }
}

3 个答案:

答案 0 :(得分:3)

由于您已创建类型BOMWorkOrder,因此请使用该类型而非匿名类型:

... select new BOMWorkOrder 
    { 
        TransactionDate = items.TRXDATE,
        TransactionId = orders.TRX_ID,
        ItemNumber = orders.ITEMNMBR,
        AssemblyQuantity = orders.Assemble_Quantity
    };

答案 1 :(得分:0)

如果您返回匿名对象列表,您将无法访问这些属性(除非您使用dynamic

您只是错过了select中的类型名称:

...
select new BOMWorkOrder
{
    TransactionData = items.TRXDATE,
    TransactionId = orders.TRX_ID,
    ItemNumber = orders.ITEMNBBR,
    AssemblyQuantity = orders.Assemble_Queantity,
}

答案 2 :(得分:0)

    select new bomWorkOrder
    {  
        TransactionDate =items.TRXDATE,
        TransactionId =orders.TRX_ID,
        ItemNumber =orders.ITEMNMBR,
        AssemblyQuantity =orders.Assemble_Quantity
    });