实体框架6 - 未加载子属性数据

时间:2013-12-22 18:47:15

标签: sql entity-framework

Complex实体上的ManagingAgent子属性没有加载数据....可能是过多的葡萄酒的结果。

我已经在数据库调用上记录了SQL,并且SQL正在返回正确的数据。

LazyLoading已停用。

public ApplicationDbContext()
        : base("DefaultConnection")
{
    this.Configuration.LazyLoadingEnabled = false;
}

聚合根

public class Complex
{
    public Complex()
    {
        Forums = new List<Forum>();
        ManagingAgent = new ManagingAgent();
    }

    [Key]
    public int ComplexId { get; set; }
    [Required]
    public string Name { get; set; }
    public string Address1 { get; set; }
    public string Address2 { get; set; }
    public string Address3 { get; set; }
    public int? PostCodeId { get; set; }
    public PostCode PostCode { get; set; }
    public int? LocationId { get; set; }
    public Location Location { get; set; }
    public int? CountyId { get; set; }
    public County County { get; set; }
    public int? ManagingAgentId { get; set; }
    public ManagingAgent ManagingAgent { get; set; }
    public int? CountOfUnits { get; set; }
    public List<Forum> Forums { get; set; }     
}

尝试1.使用包含...

public List<Complex> GetComplexesByUserId(Guid userId)
{
    using (var db = new ApplicationDbContext())
    {
        db.Database.Log = Logger;
        var complexIds = db.UserApartments.Where(r => r.UserId == userId)
                                          .Select(c => c.ComplexId).ToList();
        return db.Complexes.Where(c => complexIds.Contains(c.ComplexId))
                           .Include(m => m.ManagingAgent).ToList();
    }
}

尝试2 - 显式加载..same结果(SQL正确返回数据但未填充ManagingAgent)

public List<Complex> GetComplexesByUserId(Guid userId)
{
    using (var db = new ApplicationDbContext())
    {
        db.Database.Log = Logger;
        var complexIds = db.UserApartments.Where(r => r.UserId == userId)
                                          .Select(c => c.ComplexId).ToList();

        var list = new List<Complex>();

        foreach (var id in complexIds)
        {
            var complex = db.Complexes.Find(id);
            db.Entry(complex).Reference(m => m.ManagingAgent).Load();
            list.Add(complex);
        }

        return list;                
    }
}

所以,强迫我正在做这个负载....不好......

foreach (var id in complexIds)
{
    var complex = db.Complexes.Find(id);
    var managingAgent = db.ManagingAgents.Find(complex.ManagingAgentId);
    complex.ManagingAgent = managingAgent;
    list.Add(complex);
}

1 个答案:

答案 0 :(得分:2)

删除此行...

ManagingAgent = new ManagingAgent();

...来自Complex实体的构造函数。然后它会工作。 (通常不要在实体默认构造函数中实例化引用导航属性.EF在实现实体时通过反射调用此构造函数,并且&#34;混淆&#34;如果导航属性已经有引用。我可以&#因为我不知道对象实体的物体实现的确切机制,但是因为已经有一个被忽略的子列值被忽略了,所以解释&#34;混淆了#34;更好实例化的子实体,但只是使用ManagingAgent构造函数中无用的默认值。)