2013-08-07 26 views
0

我想弄清楚如何使用.Include()從抽象類型中選擇包含實現類型的關係實體時,以下是我嘗試執行的一個示例:如何。抽象實現類型的.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 

    } 

回答

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