EF代码优先.相关实体未加载

本文关键字:实体 加载 代码 EF | 更新日期: 2023-09-27 18:07:20

我有实体框架代码第一实体:

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();

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

Thanks in advance

EF代码优先.相关实体未加载

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

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

如果你想要延迟加载的代理,它们也应该是virtual…但是对于急切加载来说就不需要了

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

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