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

本文关键字:类型 返回 编译 查询 | 更新日期: 2023-09-27 18:19:07

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

我试着使用:

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; }
}

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

由于您已经创建了类型BOMWorkOrder,所以请使用该类型而不是匿名类型:

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

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

你只是错过了类型名称在你的select:

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