How to return a list in Entity Framework?

entity-framework

Question

I am trying to write a simple function that returns a list, but I keep getting an error at last line of code (return query.ToList()). Can anyone please help me to resolve this issue.

This is 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

The type you select in your query does not match the return type.

Try this, it will select the appropiate type in your query, so that the conversion ToList() is possible.

        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

You need to use your method return type instead of 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