实体框架一对多有条件

时间:2016-08-05 13:10:44

标签: entity-framework entity-framework-4

我有一个Job类

[Table("Jobs")]
public class Job
{
  [Key]
  [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
   [Column("fID")]
   public int ID { get; set; }

   public virtual ICollection<Note> Notes { get; set; }
}

音符类如下所示:

[Table("Note")]
public class Note
{
  [Key]
  [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
  [Column("fID")]
  public int ID{get; set;}

  [Column("fld_int_NoteTypeID")]
  public int NoteTypeID { get; set; }
}

每当我从这样的工作中请求Notes时:

 var job= context.Jobs.Include(x => x.Notes).FirstOrDefault(x => x.ID == jobId);

我希望查询隐式添加Where NoteTypeId == 8

是否有可能以某种方式添加此子句,或者每次都必须明确添加它?

1 个答案:

答案 0 :(得分:1)

解决方法怎么样?添加过滤 Notes集合 NotMapped 属性:

[Table("Jobs")]
public class Job
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    [Column("fID")]
    public int ID { get; set; }

    public virtual ICollection<Note> Notes { get; set; }

    [NotMapped]
    public ICollection<Note> FilteredNotes
    {
        get
        {
            return Notes.Where(m => m.NoteTypeId == 8);
        }
    }
}

但是这个设计的问题是,当您选择var job = context.Jobs.Include(x => x.Notes).FirstOrDefault(x => x.ID == jobId);之类的作业时,然后将所有Notes加载到内存中,然后您可以从内存中访问过滤后的注释,如job.FilteredNotes。但是当使用LazyLoading时,它有优势。

var job = context.Jobs.FirstOrDefault(x => x.ID == jobId);
var notes = job.FilteredNotes.ToList();

更新

您还可以尝试每个层次结构表(TPH) mappimg。您必须创建一个抽象类和派生类:

public abstract class Note
{
    public int Id { get; set; }
    public int NoteTypeId { get; set; }
}

public class JobNote : Note
{
}

public class OtherNote : Note
{
}

然后覆盖OnModelCreating方法:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Entity<Note>()
                .Map<JobNote>(m => m.Requires("NoteTypeId").HasValue(8))
                .Map<OtherNote>(m => m.Requires("NoteTypeId").HasValue(3)); // For example
}

请注意,我对TPH知之甚少。我只是想表现出一些暗示。请进一步了解TPH