Reputation: 523
Here is my typical scenario:
I have many c# business objects that more or less match my database design. I also have collections of these objects that I use to bind to gridviews. What is the best way to combine fields from both of these objects to my gridview (without using datatables or creating a view)
Let's say I want a gridview with the following columns: Product ID, Product Name, Product Cost, Shipping Company Name. Usually I simply get my collection of products from the database and use an item template for the shipping company name. I would then get the ShippingCompanyID in the rowdatabound event and go to the database again to get my shipping company name. I hate going to the database twice, can someone coach me on how I should approach this?
Product Class
Shipping Company Class
Upvotes: 0
Views: 246
Reputation: 44941
In cases like this, we actually include the company name in the class that is bound to the grid (Products) and join the tables in the database, usually in a view.
This way there is no extra work in code and that same view can be re-used in other scenarios, such as report generation.
Upvotes: 1
Reputation: 94643
You may use joins in Linq
to achieve the desire result.
var result = from prd in products
from cmp in companies
where prd.ShippingCompanyID == cmp.ShippingCompanyID
select new
{
ProductID=prd.ProductID,
ProductName=prd.Name,
Company=cmp.Name
};
Upvotes: 1
Reputation: 735
using LINQ, assuming products
is a collection of type Product
, and shippingCompanies
is a collection of type ShippingCompany
.
from p in products
join s in shippingCompanies on p.ShippingCompanyID equals s.ShippingCompanyID
select new { p.ProductID, p.Name, p.Cost, s.Name }
Upvotes: 1