0

Ok I've two tables with me

    Candidates
    Id   Name 
    1    Tejas
    2    Mackroy

   Experiences
   Id  Designation CandidateId isDeleted
    1   Engineer        1         true
    2   Developer       1         false 
    3   Tester          1         true
    4   Engineer        2         false
    5   Tester          2         true

The model classes are :

    public class Candidate
    {
         public int Id { get; set; }
         public string Name { get; set; }
         public virtual ICollection<Experience> Experiences { get; set; }
    }

    public class Experience
    {
         public int Id { get; set; }
         public string Designation { get; set; }
         public int CandidateId { get; set; }
         public bool isDeleted { get; set; }
    }

I wish to get GET ALL the candidates along with their Qualifications but only those where isDeleted == false .

It'll be somewhat like _DbContext.Candidates.Include("Qualifications").ToList();

So it'll be like :

{ 1 , "Tejas" , { 2, "Developer" } }, { 2, "Mackroy", { 4, "Engineer" } }

I wish to know how this can be implemented by directly using DbContext aswell as using Generic Repository .

hendrixchord
  • 4,662
  • 4
  • 25
  • 39
  • 2
    possible duplicate of [Filtering inner collection with Entity Framework 5 and Repository pattern and Unit of Work](http://stackoverflow.com/questions/13479352/filtering-inner-collection-with-entity-framework-5-and-repository-pattern-and-un) or http://stackoverflow.com/q/16798796/861716. – Gert Arnold Oct 22 '13 at 12:53

1 Answers1

1

Create custom view model and populate it with you data:

    public class  CandidateViewModel {

             CandidateViewModel() {
                Qualifications = new List<Qualifications>();
             }

             public int Id { get; set; }
             public string Name { get; set; }
             public List<Qualifications> Qualifications { get; set; }
    }

    public class Qualification {
             public int Id { get; set; }
             public string Label { get; set; }
    }
    //ViewModel

    var result = _DbContext.Candidates.Select(o => new CandidateViewModel {
                                  Id = o.Id,
                                  Name = o.Name,
                                  Qualifications = o.Experiences.Where(d => !d.IsDeleted).ToList()
    }).ToList();
freshbm
  • 5,540
  • 5
  • 46
  • 75