如何从抽象实现类型中包含.Include()属性

时间:2013-08-07 08:21:50

标签: c# entity-framework

我试图弄清楚如何使用.Include()从抽象类型中选择包含Implemented类型的关系实体时,这里是我尝试做的一个例子:

[Table("Comments")]
public abstract class Comment
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int CommentId { get; set; }
    public int UserId { get; set; }
    public virtual UserProfile User { get; set; }
    public string Content  { get; set; }
}

[Table("PostComments")]
public class PostComment : Comment
{
    public int PostId { get; set; }
    public virtual Post Post { get; set; }
}

[Table("UserProfiles")]
public class UserProfile
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int UserId { get; set; }
    [MaxLength(200)]
    public string UserName { get; set; }
    public ICollection<Comments> Comments { get; set; }
}

  using (DataContext db = new DataContext())
  {
       return db.UserProfiles.Include(x => x.Comments)
       .Single(u => u.UserId == WebSecurity.CurrentUserId);

       // Here I need a way to include Comment.Post if Comment 
       // is PostComment or some other child entity if Comment is 
       // from another inherited type

  }

1 个答案:

答案 0 :(得分:1)

你不能这样做。不同的方法可能对您更有效:

UserProfile更改为:

[Table("UserProfiles")]
public class UserProfile
{
    // ...
    public ICollection<PostComment> PostComments { get; set; }
    public ICollection<OtherComment> OtherComments { get; set; }
}

继承公共类型时,EF执行的操作是在共享表中创建一个鉴别器列。因此,当您选择PostComments时,EF生成的WHERE子句将具有类似AND type='PostComment'的内容。 (我不记得它生成的列的名称,但你明白了。)

然后你可以得到这样的数据:

var data = db.UserProfiles
                .Include("PostComments.Post")
                .Include("OtherComments.OtherData")
                .Single(p => p.UserId == WebSecurity.CurrentUserId);

如果要将所有注释用作单个列表,可以像下面这样创建:

var comments = data.PostComments.ToList<Comment>();
comments.AddRange(data.OtherComments);