2013-09-27 127 views
1

我需要幫助來查詢這三個表。 RentCommunityFeature和RentPropertyFeature與RentUnitListing有多對多的關係。我的問題是我無法獲得這三個表來查詢。我想要的是具有某些功能的所有租賃列表。例如,如果RentCommunityFeature有一個「池」,RentPropertyFeature有一個「停放」,我希望RentUnitListing中具有「Pool」和「Parking」的所有記錄。如果沒有停車比結果只顯示「池」。Linq多對多查詢

我嘗試了下面的查詢,但它給出了不正確的結果。當myCommunityFeatureId或myPropertyFeatureId爲-1時,它顯示重複的結果。如果它們在數據庫中爲空,我將它們初始化爲-1。

任何幫助將不勝感激。

var AllAds = from r in _db.RentUnitListings 
      from cf in r.RentCommunityFeatures      
      from pf in r.RentPropertyFeatures 
      where (myCommunityFeatureId > 0) ? (cf.RentCommunityFeatureID == myCommunityFeatureId && cf.RentUnitListings.) : (myCommunityFeatureId == -1) 
      where (myPropertyFeatureId > 0) ? (pf.RentPropertyFeatureID == myPropertyFeatureId) : (myPropertyFeatureId == -1) 
      select r; 

public partial class RentCommunityFeature 
{ 

    public int RentCommunityFeatureID { get; set; } 
    public string RentCommunityFeatureDescription { get; set; } 

    public virtual ICollection<RentUnitListing> RentUnitListings { get; set; } 
} 

public partial class RentPropertyFeature 
{ 


    public int RentPropertyFeatureID { get; set; } 
    public string RentPropertyFeatureDescription { get; set; } 

    public virtual ICollection<RentUnitListing> RentUnitListings { get; set; } 
} 

public partial class RentUnitListing 
{ 
    public Guid RentUnitListingID { get; set; } 
    public string RentUnitListingShortDescription { get; set; } 
    public virtual ICollection<RentCommunityFeature> RentCommunityFeatures { get; set; } 
    public virtual ICollection<RentPropertyFeature> RentPropertyFeatures { get; set; }   
} 

回答

1
var listings = _db.RentUnitListings 
    .Where(rul => rul.RentCommunityFeatures 
       .Any(rcf => rcf.RentCommunityFeatureID == myCommunityFeatureId) 
       || rul.RentPropertyFeatures 
       .Any(rpf => rpf.RentPropertyFeatureID == myPropertyFeatureId)) 
    .ToList(); 

這意味着:傳回所有擁有至少一個AnyRentCommunityFeaturemyCommunityFeatureIdOR至少一個AnyRentPropertyFeaturemyPropertyFeatureId所有目錄。 「OR」不是排他性的,因此返回的列表可能會有一個沒有「停車」功能的「游泳池」或沒有「游泳池」功能的「停車」,或者可能同時具有這兩種功能。在任何情況下,除了「游泳池」或「停車」之外,返回列表可能還有許多其他功能。

+0

這很有幫助,謝謝。 – deshergan