這些都是我的課:實體框架5 - 代碼第一陣列導航屬性一對多與接口類型
public class Post : IPost
{
public int Id { get; set; }
public virtual int[] DuplicateOf { get; set; }
public virtual ICommentInfo[] Comments { get; set; }
}
public class CommentInfo : ICommentInfo
{
public virtual string Author { get; set; }
public virtual int Id { get; set; }
public virtual string Text { get; set; }
public virtual int PostId{ get; set; }
[ForeignKey("PostId")]
public virtual Post Post { get; set; }
}
有了這個CommentConfiguration加入到OnModelCreate():
HasRequired(c => c.Post)
.WithMany(b=>(ICollection<CommentInfo>) b.Comments)
.HasForeignKey(b=>b.PostId)
.WillCascadeOnDelete(true);
我實在無法理解爲什麼屬性Comments始終爲空,以及EF爲什麼不初始化它,因爲它是虛擬的。 我也嘗試禁用懶加載,但是當我嘗試加載導航屬性context.Post.Include("Comments")
錯誤告訴我,「沒有導航屬性稱爲評論」。 所以我嘗試使用實體框架電力工具測試版3來查看實體數據模型,並且我發現,即使兩個表之間存在關係並且評論表結束也沒有表「發佈」的導航結束。
我真誠地不知道該怎麼轉,可能是數組的問題?我應該使用Icollection屬性嗎? 雖然我無法更改該屬性的類型,因爲Post正在實現一個接口。
我所看到的每一個樣本都很清晰,很容易做出工作。請幫助我..提前謝謝你。
編輯:
這是我在看link我昨天公佈後改變。
public class Post : IPost
{
public int Id { get; set; }
public virtual int[] DuplicateOf { get; set; }
public virtual ICollection<CommentInfo> Comments { get; set; }
ICommentInfo[] IPost.Comments {
get { return Comments ; }
set { Comments = (CommentInfo[])value; } }
}
唯一的例外是:System.ObjectDisposedException :The ObjectContext instance has been disposed and can no longer be used for operations that require a connection
當應用程序試圖獲得評論引發。 如果我刪除了virtual
鍵,那麼異常消失,但屬性始終爲空,並且值不會以任何方式持續存在。
EDITv2 我解決了我的問題,添加一個新的屬性,並映射到我的舊屬性。
public class Post : IPost
{
public int Id { get; set; }
public virtual int[] DuplicateOf { get; set; }
public ICommentInfo[] Comments
{
get { return ListComments.ToArray(); }
}
public List<CommentInfo> ListComments {get;set;}
}
在我PostConfiguration OnModelCreate()我用ListComments屬性作爲導航性能是這樣的:
HasMany(b => b.ListComments)
.WithRequired(c=>c.Post)
.HasForeignKey(c=>c.PostId)
.WillCascadeOnDelete(true);
現在,它完美的作品,它比我預期的更簡單,當我嘗試接收評論集合,如果我包含「ListComments」屬性,我得到Post的數組。 謝謝你的幫助!
花費時間後,我發現可能是我的類中的接口類型的問題。我試圖按照這裏的例子[http://antix.co.uk/Blog/EF4-Code-First-and-Interface-Property-Types]並改變了我的實現,但現在它引發了這個異常: System.ObjectDisposedException :ObjectContext實例已被處置,不能再用於需要連接的操作。 – 2013-02-10 11:06:30
好的,但你如何從數據庫中獲取帖子,以及你在哪裏第一次訪問'IPost.Comments'?你不能在一個聲明中這樣做。 – 2013-02-11 14:03:20