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

Kir*_*rst 19 .net linq linq-to-entities join linq-to-sql

我已经使用LINQ to SQL和Entity Framework几年了,我总是映射我的数据库关系以生成相关的导航属性.我总是使用导航属性.

我错过了什么吗?

如果我有一个Category->Products多种类型的关系,我会使用

var redProducts = context.Category.Single(c => c.Name = "red").Products;
Run Code Online (Sandbox Code Playgroud)

我经常看到人们在这个网站,在线项目和各种其他网站上进行手动连接.

var employer = from category in context.Categories
               join product in context.Products
               on category.CategoryId equals product.CategoryId
               where category.Name == "red"
               select product;
Run Code Online (Sandbox Code Playgroud)

所以为什么?使用此Join语法有什么好处?

Cra*_*ntz 9

这通常是个错误.

@George是正确的,你的两个例子在功能上是不同的,但是与joinvs非无关join.但你可以很容易地写:

var redProducts = context.Category
                         .Where(c => c.Name == "red")
                         .SelectMany(c => c.Products);
Run Code Online (Sandbox Code Playgroud)

...在功能上相同(但从可读性和可维护性POV 优于)您的join示例.