为什么使用LINQ加入一个简单的一对多的关系? [英] Why use LINQ Join on a simple one-many relationship?

查看:382
本文介绍了为什么使用LINQ加入一个简单的一对多的关系?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经使用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.

这篇关于为什么使用LINQ加入一个简单的一对多的关系?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆