问题描述
给出以下琐碎的EF示例:
Given the following trivial EF example:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Entity;
namespace EFPlay
{
public class Packet
{
public Guid Id { get; set; }
public string Name { get; set; }
public Reciever Reciever { get; set; }
}
public class Reciever
{
public Guid Id { get; set; }
public virtual ICollection<Packet> Packets { get; set; }
}
public class Context : DbContext
{
public DbSet<Reciever> Recievers { get; set; }
public DbSet<Packet> Packets { get; set; }
}
public class Program
{
static void Main(string[] args)
{
var db = new Context();
var reciever = db.Recievers.Create();
}
}
}
此时,reciever.Packets属性为null。这是否应该由EF自动初始化?有什么办法确保它是吗?
At this point the reciever.Packets property is null. Should this not be initialised automatically by EF? Is there any way to ensure that it is?
推荐答案
它为空,因为您尚未请求Entity Framework检索关联。
It's null because you haven't asked Entity Framework to retrieve the association.
有两种方法:
1 - 延迟加载 / p>
1 - Lazy Loading
var reciever = db.Recievers.SingleOrDefault();
var receiverPackets = receiver.Packets; // lazy call to DB - will now be initialized
我不喜欢这种方法,我个人关闭延迟加载,并使用其他方法
I don't like this approach, i personally turn off lazy loading, and use the other approach
2 - Eager Loading b
var receiver = db.Receivers.Include("Packets").SingleOrDefault();
这导致接收器和数据包之间的LEFT OUTER JOIN,而不是两个调用懒惰加载。
Which results in a LEFT OUTER JOIN between Receivers and Packets, instead of two calls - which is the case with lazy loading.
这是否能解答你的问题?
Does that answer your question?
这篇关于实体框架未初始化集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!