【发布时间】:2010-12-24 12:40:20
【问题描述】:
给出以下简单的 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 属性为空。这不应该由EF自动初始化吗?有没有办法确保它是?
【问题讨论】:
-
检查有什么问题:(db.Packets != null)?
-
我也有同样的问题。鉴于我们正在调用 .Create() 我不明白为什么 EF 不为集合创建代理。创建我们自己的集合实例感觉很笨拙,这与加载的实体不同(并且不会有任何跟踪):(
标签: c# database linq entity-framework collections