首页 > 代码库 > EF的三种数据加载方式

EF的三种数据加载方式

EF中有3种数据加载方式,具体如下:

延迟加载(默认): 设置导航属性为virtual

贪婪加载:不设置导航属性为virtual,并且对导航属性使用Include

显示加载:不设置导航属性为virtual,并且对导航属性使用Reference(单个对象).Load()或Collection(对象集).Load()

    public class Programm    {        public static void Main()        {            TestDbContext db = new TestDbContext();            //延迟加载            var res1 = db.Reservations;            foreach (var item in res1)            {                //do something            }            //贪婪加载            //有多个Include会全部完成加载,生成的sql命令是一条完成的            var res2 = db.Reservations.Include(r => r.Details);            //显示加载            var res3 = db.Reservations.ToList();            foreach (var item in res3)            {                var temp = db.Entry(item);                temp.Collection(i => i.Details).Load();                temp.Reference(i => i.Customer).Load();            }        }    }    public class Reservation    {        public int ReservationId { get; set; }        public string ClientName { get; set; }        public string Location { get; set; }        public List<ReservationDetails> Details { get; set; }        public Customer Customer { get; set; }    }    public class ReservationDetails    {        public int Id { get; set; }        public DateTime Time { get; set; }    }    public class Customer    {        public int Id { get; set; }        public string Name { get; set; }    }    public class TestDbContext : DbContext    {        public DbSet<Reservation> Reservations { get; set; }    }

 

EF的三种数据加载方式