Code First 延迟装入特性

使用ORM框架,基本上都会添加“延迟装入”的特性支持,当使用Entity Framwork 的objectContext与DbContext操作数据时,默认都使用“延迟装入”,也就是当我们在应用程序里通过Linq to Entity查询数据时,如果遇到关联数据尚未装入时,Entity Framwork会自动帮我买再向数据库索取相关数据,全自动地取得相关数据,大幅度降低撰写访问相关数据的程序代码。

例如:

using System;
using System.Collections.Generic;
 
namespace MVC.Models
{
    public class Gustbook
    {
        public int Id { get; set; }
        public string Message { get; set; }
        public DateTime CreatOn { get; set; }
 
        public virtual ICollection<Member> Members { get; set; }
    }
 
    public class Member
    {
        public int Id { get; set; }
 
        public string Name { get; set; }
        public string Email { get; set; }
 
        public virtual Gustbook Gusetbooks { get; set; }
    }
}

假设有个gustbook 对象要取得Message字段的值,只要输入以下程序即可:
Gustbook.Message
但如果想要取得Gustbook关联对象Member数据表中的Name字段,则通过点语法加上一个“点”与“属性名称”即可:
Gustbook.Member.Name

注意:在Code First开发时,若要取得“延迟装入”特性,必须在属性声明加上virture关键字,例如上面Member表中的
 public virtual Gustbook Gusetbooks { get; set; }
原文地址:https://www.cnblogs.com/getpower/p/5033122.html