How to return a list in Entity Framework?

entity-framework

Question

I am attempting to create a straightforward function that produces a list, however every time I run the code, I receive an error (return query.ToList() ). Could someone kindly assist me in solving this problem?

Here's the code:

Thanks.

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();
    }              
}
1
1
11/28/2013 11:35:44 AM

Accepted Answer

Your query's type selection does not match the return type.

Try this; it will choose the appropriate query type to facilitate conversion.ToList() is attainable.

        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();

        }

Alternative:

        using(var db = new POSContext())
        {
            return (from c in db.Product
                         where c.ProductId == ProductId
                         select c).ToList();
        }
2
11/28/2013 10:56:03 AM

Popular Answer

Use your method's return type rather than an anonymous type:

    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();

                }

            }


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow