Entity Framework 6 Recipes 2nd Edition(13-8)译 -> 把昂贵的属性移到其它实体

问题

你想把一个昂贵的属性移到另一个实体,这样你就可以延迟加载当前这个实体.对于一个加载昂贵的而且很少用到的属性尤其有用.

                  

解决方案

模型和上一节(Recipes 13-7)的一致,如Figure13-10所示

 

Figure 13-10. A model with a Resume entity with a Body property that contains the entire text of the applicant’s

resume. In this recipe, we’ll move the Body property to another entity

 

         我们假设(和我们上一节所做的一样)Body属性包含一个非常大的数据.我们想把这个属性移到另一个实体,以便我们能搞高延迟加载性能.

         按以下步骤把Body属性移到另一个实体:

  1. 在设计界面上右击,选择”添加”>实体.命名为”ResumeDetail”,并不勾选”创建主键”复选框.
  2. 移动Body属性到ResumeDetail实体上,你可以用”剪切/粘贴”等操作.
  3. 在设计界面上右击,选择”添加”>关联.把Resume和ResumeDetail关联里都设置为一,勾选”添加外键属性到ResumeDetail实体”复选框(查看图Figure 13-11)

 

Figure 13-11. Adding an association between Resume and ResumeDetail

  4.把关联创建的外键的名称”ResumeResumeId”修改为”ResumeId”.

  5.选择ResumeDetail实体,查看”映射明细窗口”.把实体映射到Resume表.把Body属性遇到表的Body列.把ResumeId属性映射到表的ResumeId列(参见图Figure 13-12)

 

Figure 13-12. Map the ResumeDetail entity to the Resume table. Map the ResumeId and Body properties as well

  6.在ResumeDCetail实体上,选择ResumeId属性,查看所有属性,把EntityKey属性设置为true,这样就把ResumeId属性标志为实体的主键.完成后的模型如图Figure 13-13.

 

Figure 13-13. The completed model with the Body property moved to the new ResumeDetail entity

 

         代码Listing 13-22 演示了如何使用ResumeDitail实体.

Listing 13-22. Using the ResumeDetail Entity to Lazy Load the Expensive Body Property

            using (var context = new EFRecipesEntities())

            {

                var r1 = new Resume { Title = "C# Developer", Name = "Sally Jones" };

                r1.ResumeDetail = new ResumeDetail { Body = "...very long resume goes here..." };

                context.Resumes.Add(r1);

                context.SaveChanges();

            }

 

            using (var context = new EFRecipesEntities())

            {

                var resume = context.Resumes.Single();

                Console.WriteLine("Title: {0}, Name: {1}", resume.Title, resume.Name);

                // note, the ResumeDetail is not loaded until we reference it

                Console.WriteLine("Body: {0}", resume.ResumeDetail.Body);

            }

输出结果如下:

Title: C# Developer, Name: Sally Jones

Body: ...very long resume goes here...

 

它是如何工作的

为了避免Resum实体加载昂贵的Body属性,把它移到一个新的相关的实体.通过两个实体把与底层表的访问分开.我们可以利用EF的延迟加载,Body属性仅在需要的时候加载它.这是一种相对简洁的方式,但是它在我们的模型里引入了一个额外的实体,所以需要一点额外的编码.

 

注意:          如何用CodeFirst方式把一个属性移到另一个实体的方法,请参见 http://msdn.microsoft.com/en-us/data/jj591617#2.8 . 这个过程被称为”实体分离”技术,该技术允许一个实体分布到不同的表里.

posted @ 2016-05-16 14:57  kid1412  阅读(279)  评论(0编辑  收藏  举报