Search code examples
c#databaseforeachdto

How to fill out DTO in C#


I'm have trouble reading my list of DTOs.

I wish to receive a list of DTOs from a database so I can put them in a table on the WPF part, but when I run the program there is no data in the list, and there are no errors. I do not understand why, is there something wrong with my code?

   public IList<ProductDTO> GetProducts()
{
       IList<ProductDTO>listofproducts = new List<ProductDTO>();
       ProductDTO productDto = new ProductDTO();


    using (var db = new NORTHWNDEntities())
    {
        var query = from p in db.Products

                    select new
                    {
                        Name = p.ProductName,     
                    };

        foreach (var product in query)
        {
            productDto.Name = product.Name;
            listofproducts.Add(productDto);
        }

        return listofproducts;
    }     
}

Updated VERSION:

I'm getting a error called entityexception was unhandled by user code at the end of the code (tolist)

 public IEnumerable<ProductDTO> GetProducts()
        {
            using (var db = new NORTHWNDEntities())
            {
                return db.Products.Select(m => new ProductDTO { Name = m.ProductName }).ToList();
            }
        }

Solution

  • You are adding the same reference to the list. You can fix it like this:

    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,     
                        };
            foreach (var product in query)
            {
                listofproducts.Add(new ProductDTO {Name = product.Name});
            }
            return listofproducts;
        }     
    }
    

    Or

        public IList<ProductDTO> GetProducts()
        {
            using (var db = new NORTHWNDEntities())
            {
                return db.Products.Select(m=>new ProductDTO{Name = m.ProductName}).ToList();
            }     
        }