Linq to SQL 将表映射到自身
我有一个名为 products 的表,以及一个名为 related_products 的映射表,它维护产品之间的父子关系,例如产品 SKU_ID 1 具有相关产品 2 和 2。 3.
products
+-----------------+
|SKU_ID | name |
+-----------------+
| 1 | Blah
| 2 | Blah2 |
| 3 | Blah3 |
+-----------------+
related_products
+---------+------------+
|SKU_ID_1 | SKU_ID_2 |
+---------+------------+
| 1 | 2 |
| 1 | 3 |
| 3 | 2 |
+---------+------------+
ORM 协会: products.SKU_ID 和 related_products.SKU_ID_1 之间的一对多关系 related_products.SKU_ID_2 和 products.SKU_ID 之间的一对一关系
这在我的应用程序中工作正常,但是当我查看返回的对象时可以看到,由于关系的循环性质,我似乎返回了太多数据。示例:如果我获取属于产品 SKU_ID=1 的所有相关产品,我将获取产品 2 和 2。 3 如预期。从这些产品对象中,我还可以获得他们的相关产品,然后是他们相关产品的相关产品,依此类推。
这是一个问题吗?如果是这样,我如何限制返回关联的“深度”?或者我一开始就错误地完成了映射?
I have a table called products, and a mapping table called related_products which maintains a parent-child relationship between products, e.g. product SKU_ID 1 has related products 2 & 3.
products
+-----------------+
|SKU_ID | name |
+-----------------+
| 1 | Blah
| 2 | Blah2 |
| 3 | Blah3 |
+-----------------+
related_products
+---------+------------+
|SKU_ID_1 | SKU_ID_2 |
+---------+------------+
| 1 | 2 |
| 1 | 3 |
| 3 | 2 |
+---------+------------+
ORM Associations:
OneToMany relationship between products.SKU_ID and related_products.SKU_ID_1
OneToOne relationship between related_products.SKU_ID_2 and products.SKU_ID
This works fine in my application, but when I look at the returned objects in can see that because of the circular nature of the relationships, it seems like I'm returning too much data. Example: If I get all related products belonging to product SKU_ID=1, I get products 2 & 3 as expected. From those product objects I can also get their related products, then the related products of their related products and so on and so on.
Is this a problem? and if so how can I restrict the 'depth' of the returned associations? or have I done the mapping incorrectly in the first place?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我觉得这样的协会很好。
由于Linq2sql默认是延迟加载的,所以不需要限制dept。只有在代码中使用相关产品时,您才会检索它们。 (如果您担心加载太多,只需分析 SQL,您就会看到它们加载的时间/级别)。
如果您在 DC 上使用 LoadWith LoadOptions 进行急切加载,则可能会遇到问题。我不知道该如何处理。
感谢 Jim Wooley,我知道 LoadOptions 不允许使用循环引用......
I think the association like this is fine.
Since Linq2sql is lazy loading by default, there is no need to restrict the dept. You will only retrieve the related products as soon as you are using them in your code. (In case you are worried about loading too much, just profile the sql and you will see when/to what level they are loaded).
You might run into problems in case you are eager loading using LoadWith LoadOptions on the DC. I would not know how to deal with that.
Thanks to Jim Wooley I know that LoadOptions are not allowed with circular references....