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

C# 如何从抽象实现类型中.Include()属性,c#,entity-framework,C#,Entity Framework,我试图找出如何使用.Include()从抽象类型中选择包含已实现类型的关系实体时,下面是一个我尝试执行的示例: [Table("Comments")] public abstract class Comment { [Key] [DatabaseGenerated(DatabaseGeneratedOption.Identity)] public int CommentId { get; set; } public int UserId { get; set; }

我试图找出如何使用.Include()从抽象类型中选择包含已实现类型的关系实体时,下面是一个我尝试执行的示例:

[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

  }
[表(“注释”)]
公共抽象类注释
{
[关键]
[数据库生成(DatabaseGeneratedOption.Identity)]
public int CommentId{get;set;}
public int UserId{get;set;}
公共虚拟用户配置文件用户{get;set;}
公共字符串内容{get;set;}
}
[表(“后指令”)]
公共类后指令:注释
{
公共int PostId{get;set;}
公共虚拟Post{get;set;}
}
[表(“用户配置文件”)]
公共类用户配置文件
{
[关键]
[数据库生成(DatabaseGeneratedOption.Identity)]
public int UserId{get;set;}
[MaxLength(200)]
公共字符串用户名{get;set;}
公共ICollection注释{get;set;}
}
使用(DataContext db=newdatacontext())
{
返回db.UserProfiles.Include(x=>x.Comments)
.Single(u=>u.UserId==WebSecurity.CurrentUserId);
//在这里,我需要一种方法,包括评论。张贴如果评论
//是PostComment或其他子实体(如果注释是
//来自另一个继承的类型
}

你不能这样做。不同的方法可能更适合您:

UserProfile
更改为:

[Table("UserProfiles")]
public class UserProfile
{
    // ...
    public ICollection<PostComment> PostComments { get; set; }
    public ICollection<OtherComment> OtherComments { get; set; }
}
如果要将所有注释用作单个列表,可以按如下方式创建:

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