6

我在查詢Linq To Entities中的多對多關係時遇到問題。 我基本上是試圖複製使用LINQ此查詢:實體框架 - Linq To Entities - 多對多查詢問題

Select * 
FROM Customer 
LEFT JOIN CustomerInterest ON Customer.CustomerID = CustomerInterest.CustomerID 
LEFT JOIN Interest ON CustomerInterest.InterestID = Interest.InterestID 
WHERE Interest.InterestName = 'Football' 

我環顧四周淨並沒有真正找到如何做到這一點任何合適的例子。我已經得到的最接近的是:

List<Customer> _Customers = (from _LCustomers in _CRM.Customer.Include("CustomerInterest.Interest") 
            where _LCustomers.CustomerInterest.Any(x => x.Interest.InterestName == "Football") 
            select _LCustomers).ToList(); 

這樣做的問題是,如果一個客戶有一個以上的興趣,其中之一是「足球」,那麼將返回所有的人。我也看到了All(),它具有相反的問題,即只有當他們有一個興趣時纔會返回,如果他們有兩個,而其中一個不是足球,則返回任何東西。

任何人有任何想法?

+0

請看看這個問題 - http://stackoverflow.com/questions/1535443和這個職位 - http://blogs.msdn.com/b/alexj/archive/2009/10/13/tip -37-如何做-DO-A-有條件include.aspx。 – Kniganapolke 2010-05-25 12:39:25

回答

3

我不確定你想獲得什麼。有客戶興趣和興趣的客戶名單?只需根據客戶的興趣開始查詢。

context.CustomerInterest. 
    Where(ci => ci.Interest.InterestName == "Football"). 
    Select(ci => new 
    { 
     Customer = ci.Customer, 
     CustomerInterest = ci, 
     Interest = ci.Interest 
    }); 

但是這是非常多餘的。爲什麼不只是獲得匹配的客戶利益?

IEnumerable<CustomerInterest> customerInterests = context.CustomerInterest. 
    Where(ci => ci.Interest.InterestName == "Football"); 

您仍然可以訪問其他信息,而無需明確存儲它。

foreach (CustomerInterest customerInterest in customerInterests) 
{ 
    DoSomething(customerInterest); 
    DoSomething(customerInterest.Customer); 
    DoSomething(customerInterest.Interest); 
} 
+0

好的想法是用一個數據庫命中的客戶作爲查詢的基礎返回一個包含所有相關數據的客戶。 返回的數據將被序列化並在單個wcf調用中返回給客戶端(用於客戶維護屏幕)。 正如我們試圖保持客戶端苗條和儘可能通用客戶端沒有在EDMX的實體的概念,它只與反序列化的XML和適用於此。 我想避免匿名類型,並返回一個Customer對象只有與where子句匹配的相關數據。 – 2009-04-27 15:04:24

1

如果你想保持它的通用性,更好的方法是去實體sql [Esql]。 Coz L2E不支持linq查詢中集合的位置。

不能使用

customer.Interests.Where(利息=> interest.Name == '足球')

查詢應該是這樣..

context.CreateQuery(@"SELECT VALUE Customer FROM Customer WHERE EXISTS(SELECT VALUE FROM CustomerInterest WHERE CustomerInterest.Ineterest.Name = 'FootBall')).Include("Interest");

希望能幫助到你!

+0

不會掉到esql的解決方案只是覺得像黑客雖然?你失去了所有的智能感知以及所有應該使用EF的點。當然也可以在DbReader中執行它。 – 2009-07-31 22:16:32

0

這對於LINQT來說非常重要。嘗試在你的數據庫中使用視圖,或像Deepak N說的那樣工作。 最佳

7

試試這個,

var result = from c in ctx.Customer 
      from i in c.Interest 
      where i.InterestName == "Football" 
      select c; 

希望這有助於

雷。

2
 var results = from c in _CRM.Customer 
         from ci in c.Interests 
         join i in _CRM.Interests 
         on ci.ID equals i.ID 
         where i.Interest = "Football" 
         select c;