1

I need help to query this three tables. RentCommunityFeature and RentPropertyFeature has a many to many relationship with RentUnitListing. My problem is i can't get these three tables to query. What i want is all those rentlistings that has certain features. for example if RentCommunityFeature has a "pool" and RentPropertyFeature has a "parking", i want all the records in RentUnitListing that has "Pool" and "Parking". If no parking than result should show only with "Pool".

I tried the below query but it gives incorrect results. It shows duplicate results when myCommunityFeatureId or myPropertyFeatureId is -1. I have initializes them to -1 if they are empty in DB.

Any help would be greatly appreciated.

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

1 回答 1

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

这意味着:返回所有包含至少一个( Any)RentCommunityFeaturemyCommunityFeatureId OR 至少一个( Any)RentPropertyFeature和 的 列表myPropertyFeatureId。“OR”不是唯一的,因此返回的列表可能有一个没有“停车”功能的“游泳池”或一个没有“游泳池”功能的“停车”,或者可能两者都有。在任何情况下,除了“游泳池”或“停车”之外,返回的列表可能还有许多其他功能。

于 2013-09-27T19:19:09.647 回答