【问题标题】:Entity Framework 5 - Apply filter loading related entities using IncludeEntity Framework 5 - 使用 Include 应用过滤器加载相关实体
【发布时间】:2013-10-22 12:30:23
【问题描述】:

好的,我有两张桌子

    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

模型类是:

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

我希望获得 GET ALL 候选人以及他们的资格,但仅限于那些 isDeleted == false

有点像 _DbContext.Candidates.Include("Qualifications").ToList();

所以它会是这样的:

{ 1 , "光辉" , { 2, "开发者" } }, { 2, "Mackroy", { 4, "工程师" } }

我想知道如何通过直接使用 DbContext 以及使用 Generic Repository 来实现。

【问题讨论】:

标签: asp.net asp.net-mvc entity-framework asp.net-mvc-4 entity-framework-5


【解决方案1】:

创建自定义视图模型并使用您的数据填充它:

    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();

【讨论】:

  • 这是延迟加载它。有没有办法只加载未删除的作品?
猜你喜欢
  • 2016-10-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多