EF Code First。相关实体未加载

时间:2015-08-11 07:59:59

标签: c# entity-framework code-first

我已获得实体框架代码优先实体:

public class Customer
{
   public long Id { get; set; }
   public ICollection<ServiceAccount> Accounts { get; set; }
}

public class Service
{
   public long Id { get; set; }
}

public class ServiceAccount
{
   public long Id { get; set; }
   public Customer Customer { get; set; }
   [Required()]
   public Service Service { get; set; }
}

假设客户有一些服务帐户。但是可能存在一些默认帐户,这些帐户不受任何客户限制。每个帐户都用于具体的服务。 此实体具有以下配置:

// Customer Configuration:
base.ToTable("Customers");
base.HasKey(x => x.Id);
base.HasMany(x => x.ServiceAccounts)
    .WithOptional(x => x.Customer)
    .WillCascadeOnDelete();
// For Service:
base.ToTable("Services");
base.HasKey(x => x.Id);
// For Account:
base.ToTable("Accounts");
base.HasKey(x => x.Id);
base.HasOptional(x => x.Customer)
    .WithMany(x => x.Accounts);
base.HasRequired(x => x.Service)
    .WithMany();

问题是,当我加载客户时,他的所有帐户也被加载,但他们的服务设置为null。为什么没有加载?

提前致谢

2 个答案:

答案 0 :(得分:3)

您需要加载实体。根据您的评论:

IQueryable<Customer> customers = Customers.Include(x => x.Accounts.Select(y => y.Service));

如果您想要延迟加载的代理,它们也应该是virtual ...但是对于急切加载它没有必要

答案 1 :(得分:1)

延迟加载相关实体需要框架来创建实体的代理。尝试将导航属性设为虚拟:

public class ServiceAccount
{
   public long Id { get; set; }
   public virtual Customer Customer { get; set; }
   [Required]
   public virtual Service Service { get; set; }
}

或者,可以使用Include急切加载属性,或者甚至可以使用Load显式加载它们。

有关详细信息,请参阅https://msdn.microsoft.com/en-us/data/jj574232.aspx