为什么在简单的一对多关系上使用 LINQ Join? [英] Why use LINQ Join on a simple one-many relationship?
问题描述
我已经使用 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.
我错过了什么吗?
如果我有一个 Category->Products
一对多类型的关系,我会使用
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;
那么 - 为什么?使用这种 Join
语法有什么好处?
So - why? What are the benefits of using this Join
syntax?
推荐答案
@George 是正确的,您的两个示例在功能上有所不同,但与 join
与非 join
无关.但是你可以很容易地写:
@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);
...在功能上与您的 join
示例完全相同(但从可读性和可维护性 POV 来看,优于).
...which is functionally identical (but superior from a readability and maintainability POV) to your join
example.
这篇关于为什么在简单的一对多关系上使用 LINQ Join?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!