LINQ等效于联接查询;

本文关键字:查询 于联接 LINQ | 更新日期: 2023-09-27 18:27:58

如果我使用,通常在t-sql中

SELECT *
FROM Orders
INNER JOIN Customers
ON Orders.CustomerID=Customers.CustomerID;

它返回所有表的所有列,如何在linq中实现这一点?

尝试:

var query = from siparis in db.Siparis
            join kazan in db.Kazan on siparis.ID equals kazan.Siparis_ID into Joined
            select Joined;

但它只返回对象,而不是所有对象。

LINQ等效于联接查询;

您需要返回两个对象,或者从每个对象中返回一个选择。这是在你的问题的评论中指定的。但我只是觉得举个例子会有所帮助。

var query = from siparis in db.Siparis
            join kazan in db.Kazan on siparis.ID equals kazan.Siparis_ID 
            select new { 
                         siparis, 
                         kazan
                       };

var query = from siparis in db.Siparis
            join kazan in db.Kazan on siparis.ID equals kazan.Siparis_ID 
            select new { 
                         SiparisID = siparis.ID, 
                         KazanID = kazan.ID,
                         SiparisColumnX = sipariz.X,
                         KazanColumnX = kazan.X
                       };

这是等效的

var query = from siparis in db.Siparis
               join kazan in db.Kazan on siparis.ID equals kazan.Siparis_ID
               select siparis;

为了获得结果,在末尾添加.ToList,如

var query = (from siparis in db.Siparis
               join kazan in db.Kazan on siparis.ID equals kazan.Siparis_ID
               select siparis).ToList();