为什么使用LINQ加入一个简单的一对多的关系?关系、简单、LINQ

2023-09-02 01:30:59 作者:愚心

我已经使用LINQ to SQL和实体框架几年以来,我一直都映射到我的数据库关系,以生成相关的导航性能。我总是用导航属性。

I've been using LINQ to SQL and Entity Framework for a few years and I've always mapped my database relationships to generate the relevant navigation properties. And I always use the navigation properties.

我缺少的东西?

如果我有一个类别 - >产品一对多类型的关系,我会用

If I have a Category->Products one-many type relationship, I would use

var redProducts = context.Category.Single(c => c.Name = "red").Products;

我经常看到人们在做手工加入,遍布这个网站,在网上的项目和各种其他网站。

I regularly see people doing manual joins, all over this site, in projects online, and various other websites.

var employer = from category in context.Categories
               join product in context.Products
               on category.CategoryId equals product.CategoryId
               where category.Name == "red"
               select product;

那么 - 为什么?什么是使用的好处,这个加入语法?

推荐答案

它通常是一个错误。

@George是正确的,你的两个例子是,其中有无关加入了一种功能不同的与非 - 加入,但是。但是你可以很容易地写:

@George is correct that your two examples are functionally different in a way which has nothing to do with join vs non-join, however. But you could just as easily write:

var redProducts = context.Category
                         .Where(c => c.Name == "red")
                         .SelectMany(c => c.Products);

...这是功能相同(但卓越的从可读性和可维护性POV)到你的加入的例子。

...which is functionally identical (but superior from a readability and maintainability POV) to your join example.