For one to one relationships things are easy.
When it comes to one to many or many to many problems appear... I am not using an ORM tool now for many reasons and i am wondering when i want to get data whether it is better to reassemble one to many relationship using multiple queries or in code..For example.. Having a class Category and a class Product...
A product table has a collumn for category id (one category many products).
So for my full catalog is it better to execute 2 queries to get the categories and products i want and then populate for each category its products List ? (It is very easy with LINQ) ..
Or i should call query for each category ? Like select id from products where category_i开发者_开发问答d=5;
Also i dont know how to name the functions like to set whether i want to fetch the other side of the relationship or not..
You should always use the least number of queries possible to retrieve your data. Executing one query per category to load the products is known as the N+1 problem, and can quickly cause a bottleneck in your code.
As far as what to name your methods that specify your fetch plans, name them after what the method actually does, such as IncludeProducts or WithProducts.
If you want to retrieve all categories and all their products, you can either select all categories and then select all products in two queries, or you can select in one query and group.
To use just one query, select an inner join for your two tables
SELECT c.*, p.*
FROM Category c INNER JOIN Product p ON c.CategoryId = p.CategoryId
and then construct business objects from the resulting dataset
result.GroupBy(r => r.CategoryId).Select(group =>
new Category(/* new Category using c.* columns */)
{
Products = /* new list of Products from p.* values */
});
But I have to ask - why aren't you using an ORM?
精彩评论