如何从抽象实现类型中包含()属性
本文关键字:包含 属性 类型 抽象 实现 | 更新日期: 2023-09-27 18:26:45
我试图弄清楚如何在从抽象类型中选择包含Implemented类型的关系实体时使用.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
}
你不能这样做。不同的方法可能更适合您:
将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);