Search code examples
c#linqexceptionforeachdto

entity exception was unhandled by user code


I am getting an error called "entity exception was unhandled by user code" in the foreach loop. Why is this happening? What am i doing wrong?

    public IList<ProductDTO> GetProducts()
    {
        IList<ProductDTO> listofproducts = new List<ProductDTO>();
        using (var db = new NORTHWNDEntities())
        {
            var query = from p in db.Products
                        select new
                                   {
                                       Name = p.ProductName,
                                   };

The error happens right her in the foreach.

                *foreach (var product in query)*
                {
                    listofproducts.Add(new ProductDTO { Name = product.Name });
                }
            }
        return listofproducts;

    }

Solution

  • First of all check if you can access data source. If it is fine then you need to check your query structure. You are iterating through the query but not through query results. Use ToList method to convert the query to List to iterate through it. You need to to use Enumerable.ToList method to convert the query results to list.

    var query = (from p in db.Products
                  select new
                  {
                        Name = p.ProductName,
                  }).ToList();
    
    foreach (var product in query)*
    {
          listofproducts.Add(new ProductDTO { Name = product.Name });
    }
    

    You can directly create object of ProductDTO using projection.

    IList<ProductDTO> listOfProcuts = (from p in db.Products
                                       select new ProductDTO 
                                       {
                                           Name = p.ProductName,
                                       }).ToList();
    
    return listOfProcuts ;