1

我首先使用 Entity Framework 4.1 代码,我有两个实体和一个抽象类,这两个实体都继承自。

public abstract class Customer
{
    public long CustomerId { get; set; }
    public string Rating { get; set; }
    public int FinancialStatusValue { get; internal set; }
}

public class Organization : Customer
{
    public string Name { get; set; }
    public string Name2 { get; set; }
    public string LegalName { get; set; }
    public string OrganizationNumber { get; set; }
    public string Vat { get; set; }
    public string Duns { get; set; }
    public Organization HeadQuarter { get; set; }
    public virtual ICollection<Organization> ChildOrganizations { get; set; }
}

我将我的模型映射为:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
        modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();

        modelBuilder.Entity<Customer>().ToTable("Customer");
        modelBuilder.Entity<Organization>().ToTable("Organization");

        modelBuilder.Entity<Organization>().HasOptional(h => h.HeadQuarter)
            .WithMany(c => c.ChildOrganizations)
            .HasForeignKey(o => o.ParentId);

 }

然后我使用以下方式查询组织:

var org = ctx.Customers.OfType<Organization>().Single(c => c.CustomerId == 259033);

ParentId 已填充,但 HeadQuarter 和 ChildOrganizations 始终为空。

我错过了什么?

4

1 回答 1

2

您可以使用以下方法预先加载导航属性Include

var org = ctx.Customers.OfType<Organization>()
    .Include(o => o.HeadQuarter)
    .Include(o => o.ChildOrganizations)
    .Single(c => c.CustomerId == 259033);

您还可以利用延迟加载,它会在您第一次访问导航属性时加载它。您必须将导航属性声明为virtual. (你这样做只是为了ChildOrganizations而不是为了HeadQuarter。)

请注意,这Include只会加载您确切指定的导航属性。它不会加载您的整个树结构,即不加载Organization.ChildOrganizations.ChildOrganizations等。

于 2011-10-10T14:21:50.980 回答