简体   繁体   English

从关系数据库映射

[英]Mapping from relational database

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.. 由于许多原因,我现在不使用ORM工具,我想知道何时要获取数据,是否最好使用多个查询或代码来重组一对多关系。

For example.. Having a class Category and a class Product... 例如,..具有类Category和类Product ...

A product table has a collumn for category id (one category many products). 产品表中有一个类别ID的列(一个类别中有许多产品)。

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 ? 因此,对于我的完整目录,是否最好执行2个查询来获取我想要的类别和产品,然后为每个类别填充其产品列表? (It is very easy with LINQ) .. (使用LINQ非常容易。)

Or i should call query for each category ? 还是我应该为每个类别致电查询? Like select id from products where category_id=5; 就像select id from products where category_id=5;一样select id from products where category_id=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. 每个类别执行一次查询以加载产品被称为N + 1问题,并且可能很快导致代码瓶颈。

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. 至于指定获取计划的方法的命名方式,请以该方法实际执行的操作来命名,例如IncludeProducts或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? 但是我不得不问-为什么不使用ORM?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM