实体框架未初始化集合
给出以下简单的 EF 示例:
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 自动初始化吗?有什么办法可以保证是这样吗?
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();
}
}
}
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
它为空,因为您尚未要求实体框架检索关联。
有两种方法可以做到这一点:
1 - 延迟加载
我不喜欢这种方法,我个人关闭延迟加载,并使用其他方法
2 - 急切加载
这会导致接收器和数据包之间出现左外连接,而不是两次调用 - 这是延迟加载的情况。
这能回答你的问题吗?
It's null because you haven't asked Entity Framework to retrieve the association.
There are two ways to do this:
1 - Lazy Loading
I don't like this approach, i personally turn off lazy loading, and use the other approach
2 - Eager Loading
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?
为什么不在构造函数中初始化它...然后您可以确保每次使用该类的新实例时该字段都已初始化并可供使用。
PS:我不喜欢一排有两个“Reciever Reciever”字样。如果它能编译的话我会感到惊讶。
Why don't you initialize it in a constructor... Then you can be sure averytime you use a new instance of that class this field has already been initialized and is ready to use.
PS: I don't like the two 'Reciever Reciever' words on one row. I would be surprised if it would compile.