[英]linq to entites left outer join
我正在努力向實體留下外連接。 我有兩個實體(表):
Listings
{
ListingID,
MakeID (nullable)
}
Makes
{
MakeID,
Description
}
我想在LINQ中寫這樣的東西:
select listings.listingID
,listings.makeid
, IsNull(makes.Description, 'NA')
from listings
left outer join makes
on listings.makeid = makes.makeid
以下是實現左連接的解決方案。 在其他資源方面,我真的建議嘗試使用linq pad: http : //www.linqpad.net/這對Linq來說是一個很棒的學習工具。
// Listing class/container/table
public class Listing
{
public string ListingID {get;set;}
public Int32? MakeID {get;set;}
}
// Make class/container/table
public class Make
{
public Int32 MakeID {get;set;}
public string Description {get;set;}
}
public class Main
{
public static void LinqMain()
{
// Populate the listing table with data
List<Listing> listings = new List<Listing>()
{
new Listing() { ListingID = "Test 1", MakeID = 1 },
new Listing() { ListingID = "Test 2", MakeID = 1 },
new Listing() { ListingID = "No Make", MakeID = null },
new Listing() { ListingID = "Test 3", MakeID = 3 },
new Listing() { ListingID = "Another Makeless", MakeID = null }
};
// Populate the makes table with data
List<Make> makes = new List<Make>()
{
new Make() { MakeID = 1, Description = "Make 1"},
new Make() { MakeID = 2, Description = "Make 2"},
new Make() { MakeID = 3, Description = "Make 3"},
new Make() { MakeID = 4, Description = "Make 4"}
};
// Return the left join on Make Id
var result = from l in listings
// These two lines are the left join.
join leftm in makes on l.MakeID equals leftm.MakeID into leftm
from m in leftm.DefaultIfEmpty()
// To ensure the select does not get bogged down with too much logic use the let syntax
let description = m == null ? "NA" : m.Description
select new { l.ListingID, l.MakeID, description };
}
結果變量將包含:
任何告訴你使用.DefaultIfEmpty()作為LINQ to Entities外連接的一部分的人實際上並沒有嘗試過它! Tt根本不起作用 - 至少在.NET 3.5 SP1中是這樣。
這位博主告訴你應該如何實際做到這一點。 本質上,.NET 默認情況下在LINQ to Entities中執行外連接,因此您應該省略.DefaultIfEmpty()。 對於多個外部聯接,您必須嵌套查詢組以保持其上下文清晰。
http://oddiandeveloper.blogspot.com/2008/12/testable-left-outer-join-in-linq-to.html
這應該有所幫助,這是我之前發表的一篇博文,應該仍然具有相關性,也可能有助於測試性。
在生成實體模型時還要確保外鍵已到位,它將幫助您設置依賴項。
不要在開發機器前面檢查,但這樣的事情可能呢?
var x = from l in listings
join m in makes on l.makeid equals m.makeid into g
from ma in g.DefaultIfEmpty()
select new
{
l.listingID,
l.makeid,
(ma.Description == null ? "NA" : ma.Description)
};
如果您有任何問題,請告訴我,我會檢查我的工作電腦。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.