LINQ等效于连接查询;

时间:2013-08-17 13:04:46

标签: c# linq linq-to-sql

通常在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;

但它只返回我的对象​​,而不是一切。

2 个答案:

答案 0 :(得分:1)

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

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
                       };

答案 1 :(得分:0)

这是等效的

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();