Posts

Showing posts from September, 2017

Clean up your LINQ with Load Expressions

Often times in an application, you will need data from across several tables. One approach to get all this data at once is to use the LINQ .Include() function, which will pull in all the data of the specified parent or child table. However, this can often be too heavy, as you may not need every column so you end up pulling more data from the database than is required. When this is the case, the best practice is to use a Data Transfer Object or DTO which is one flat object that combines properties from parents and children. Below, I demonstrate a simple use of a DTO, using . Include() var products = Uow.Context.Products.Include(x => x.ParentTable).Include(x => x.ChildTable).ToList(); var dtoList = new List<ProductDto>(); foreach ( var product in products) { var dto = new ProductDto{ // Copy over properties ... // Copy over parent properties ... // Copy over child properties ... }; dtoList.Add(dto); } As I mentioned before, this i