如何在实体框架中返回一个列表?

时间:2013-11-28 10:52:59

标签: entity-framework

我正在尝试编写一个返回列表的简单函数,但是在最后一行代码(return query.ToList())中我一直收到错误。任何人都可以帮我解决这个问题。

这是代码。

感谢。

List<POS2012.Models.Entities.Products> GetItemOrPack(String ProductId, bool Ischecked)
{
    using(var db = new POSContext())
    {
        var query = (from c in db.Product
                     where c.ProductId == ProductId
                     select new { c.PackCostPrice, c.PackSalePrice});

        return query.ToList();
    }              
}

4 个答案:

答案 0 :(得分:1)

问题是select new { c.PackCostPrice, c.PackSalePrice})正在将Product投射到匿名对象中。

然后,而不是返回List<POS2012.Models.Entities.Products>,而是实际返回List<#AnonymousType>

如果您只需要PackCostPricePackSalePrice,请相应地更改方法。

答案 1 :(得分:1)

您在查询中选择的类型与返回类型不匹配。

试试这个,它会在您的查询中选择适当的类型,以便转换ToList()

        using(var db = new POSContext())
        {
            var query = (from c in db.Product
                         where c.ProductId == ProductId
                         select new POS2012.Models.Entities.Products ()
                        { 
                           PackCostPrice = c.PackCostPrice, 
                           PackSalePrice = c.PackSalePrice
                        });

            return query.ToList();

        }

替代:

        using(var db = new POSContext())
        {
            return (from c in db.Product
                         where c.ProductId == ProductId
                         select c).ToList();
        }

答案 2 :(得分:1)

您需要使用方法返回类型而不是匿名类型:

    List<POS2012.Models.Entities.Products> GetItemOrPack(String ProductId, bool Ischecked)
            {
                using(var db = new POSContext())
                {
                    var query = (from c in db.Product
                                 where c.ProductId == ProductId
                                 select newPOS2012.Models.Entities.Products{ 
                       PackCostPrice = c.PackCostPrice, 
                       PackSalePrice = c.PackSalePrice});

                    return query.ToList();

                }

            }

答案 3 :(得分:0)

select new POS2012.Models.Entities.Products代替select new,如下所示

        List<POS2012.Models.Entities.Products> GetItemOrPack(String ProductId, bool Ischecked)
    {
        using (var db = new POSContext())
        {
            var query = (from c in db.Product
                         where c.ProductId == ProductId
                         select new POS2012.Models.Entities.Products { c.PackCostPrice, c.PackSalePrice });

            return query.ToList();

        }

    }