天天看點

EntityFramework 實體拆分和表拆分

兩個概念:

實體拆分:一個實體拆分成多個表,如 Blog 實體,可以拆分成 Blogs 和 BlogDetails 兩個表。

表拆分:一個表拆分成多個實體,如 Posts 表,可以拆分成 Post 和 PostDetail 兩個實體。

配置代碼:

映射效果:

EntityFramework 實體拆分和表拆分

測試代碼:

測試結果為 Blogs 和 BlogDetails 表中,分别産生一條資料,即使 Remark 的值為空。

EntityFramework 實體拆分和表拆分

測試結果為 Posts 表中産生一條資料,注意映射配置中的這段代碼:<code>modelBuilder.Entity&lt;PostDetail&gt;().HasRequired(t =&gt; t.Post).WithRequiredPrincipal(t =&gt; t.PostDetail);</code>,我們一般在外鍵配置的時候會用到 HasRequired,Required 表示的意思是必須,還有一種寫法是:<code>modelBuilder.Entity&lt;PostDetail&gt;().HasOptional(t =&gt; t.Post).WithOptionalPrincipal(t =&gt; t.PostDetail);</code>,關鍵詞 Optional,但映射會抱下面錯誤:The entity types 'Post' and 'PostDetail' cannot share table 'Posts' because they are not in the same type hierarchy or do not have a valid one to one foreign key relationship with matching primary keys between them.

其實我的想法是,在上面測試代碼中,用了兩個 Add(而不是一個 Add,然後用 PostDetail 屬性指派),那會不會在 Posts 表中産生兩條資料,但顯然沒有,因為我們在映射配置的時候,使用的是 Required,可以了解為“強制合并為一個表”,不論你怎麼添加資料,都會隻添加一條資料,另外,需要注意的是,在上面表拆分示例中,主實體是 Post,是以,如果隻有 <code>context.PostDetails.Add(new PostDetail { Remark=""});</code>,會抱下面錯誤:Invalid data encountered. A required relationship is missing. Examine StateEntries to determine the source of the constraint violation.

本文轉自田園裡的蟋蟀部落格園部落格,原文連結:http://www.cnblogs.com/xishuai/p/ef-entity-table-splitting.html,如需轉載請自行聯系原作者

繼續閱讀