Entity Framework Uninitialised Collection
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 开发者_如何学PythonId { 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?
It's null because you haven't asked Entity Framework to retrieve the association.
There are two ways to do this:
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
var receiver = db.Receivers.Include("Packets").SingleOrDefault();
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?
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.
精彩评论