1


使用实体框架,我应该如何从对象列表中加载对象?例子。

public class Phone
{
    public int Id { get; set; }
    public string Type { get; set; }
    public Corporation Corp { get; set; }
}

public class Corporation 
{
    public int Id { get; set; }
    public string Name { get; set; }
    public List<Phone> Phones { get; set; }
}

// And now, when I get a Corporation class from entity framework,
//I can't access the Phones. I get an error: The value canot be null.
_db.Corporations.First().Name; // Works
_db.Corporations.First().Phones.First().Type; // Fails

我应该如何加载列表属性?

4

1 回答 1

3

将相关实体标记为虚拟以默认启用延迟加载。

class Corporation
{
   public int Id {get;set;}
   public virtual List<Phone> Phones {get;set;}
}
class Phone
{
   public int Id {get;set;}
   public virtual Corporation Corp {get;set;}
}
于 2012-12-05T18:50:55.627 回答