2017-06-27 53 views
0

我有一個DbSet<DtoProfile>。 現在我想過濾我的配置文件。困難的實體框架查詢

我的模型:

public class DtoProfile { 
    public IList<DtoLookingFor> LookingFor { get; set; } = new List<DtoLookingFor>(); 
    public virtual DtoSearch Search { get; set; } 
    public Guid? SearchId { get; set; } 
} 
public class DtoLookingFor 
{ 
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)] 
    public Guid Id { get; set; } 
    public LookingFor LookingFor { get; set; } 
} 
public enum LookingFor 
{ 
    A, B, C, D, E 
} 
public class DtoSearch 
{ 
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)] 
    public Guid Id { get; set; } 
    public virtual ICollection<DtoLookingFor> LookingFor { get; set; } 
} 

實施例: Profile1的具有LookingFor A,B,C,並用LookingFor乙搜索,C
Profile2的具有LookingFor B,d
Profile3的具有LookingForË
Profile1的應獲取所有配置文件,其中LookingFor是B或C.(例如Profile1和Profile2)

我該如何做到這一點IQueryable<DtoProfile>? 我已經有DtoSearch反對從數據庫加載,可與dtoSearch.LookingFor訪問所有的DtoLookingFor

+0

我添加了一個解決方案,需要一個DtoProfile並返回匹配相關的配置文件(包括其本身 - 因爲你想)lmk如果它適合你或它不是你的意思。 –

回答

0

我會改變屬性名爲「LookingFor」,實在是令人困惑,你有太多的這些,它也是類名稱。

,如果你選擇輸入該工作示例將帶給您配置文件1 - >配置文件1 + PROFILE2

static void Main(string[] args) 
    { 
     List<DtoProfile> profiles = new List<DtoProfile>(); 
     var profile1 = new DtoProfile 
     { 
      LookingFor = new List<DtoLookingFor> { new DtoLookingFor { LookingFor = LookingFor.A }, new DtoLookingFor { LookingFor = LookingFor.B }, new DtoLookingFor { LookingFor = LookingFor.C } }, 
      Search = new DtoSearch 
      { 
       LookingFor = new List<DtoLookingFor> { new DtoLookingFor { LookingFor = LookingFor.B }, new DtoLookingFor { LookingFor = LookingFor.C } }, 
      }, 
      SearchId = new Guid("10000000-0000-0000-0000-000000000000") 
     }; 

     var profile2 = new DtoProfile 
     { 
      LookingFor = new List<DtoLookingFor> { new DtoLookingFor { LookingFor = LookingFor.B }, new DtoLookingFor { LookingFor = LookingFor.D } }, 
      SearchId = new Guid("20000000-0000-0000-0000-000000000000") 

     }; 

     var profile3 = new DtoProfile 
     { 
      LookingFor = new List<DtoLookingFor> { new DtoLookingFor { LookingFor = LookingFor.E } }, 
      SearchId = new Guid("30000000-0000-0000-0000-000000000000") 

     }; 


     profiles.AddRange(new List<DtoProfile> { profile1, profile2, profile3 }); 

     IEnumerable<DtoProfile> query = GetMatchesForProfile(profiles, profile1); 

     Console.WriteLine("Found: " + string.Join(",", query.Select(m => m.SearchId))); 
     //result: Found: 10000000-0000-0000-0000-000000000000,20000000-0000-0000-0000-000000000000 
    } 

    private static IEnumerable<DtoProfile> GetMatchesForProfile(List<DtoProfile> profiles, DtoProfile profileToMatch) 
    { 
     return profiles.Where(searchProfile => profileToMatch.Search.LookingFor.Any(m => searchProfile.LookingFor.Any(z => z.LookingFor == m.LookingFor))); 
    }