简体   繁体   English

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

[英]EF Code First. Related Entity is not loading

I've got Entity Framework Code First Entities: 我有实体框架代码第一实体:

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; }
}

It is supposed that a Customer has some Accounts for the Services. 假定客户有一些服务帐户。 But there can be some default Accounts, which are not bounded to any Customer. 但是可以有一些默认帐户,它们不受任何客户的约束。 And each Account is used for a concrete Service. 每个帐户都用于具体服务。 This Entities have the following Configuration: 该实体具有以下配置:

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

The problem is, when I load a Customer, all his Accounts are loaded too, but they have their Service set to null. 问题是,当我加载一个客户时,他的所有帐户也都被加载了,但是他们的服务设置为空。 Why it is not loaded? 为什么不加载?

Thanks in advance 提前致谢

You need to load the entities. 您需要加载实体。 Based on your comment: 根据您的评论:

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

They should also be virtual if you want proxies for lazy loading... but for eager loading it's not necessary 如果您想要代理进行延迟加载,它们也应该是virtual ...但是对于急于加载的用户则没有必要

Lazy loading of related entities requires the framework to create a proxy of your entity. 延迟加载相关实体需要框架为您的实体创建代理。 Try making your navigation properties virtual: 尝试将导航属性设置为虚拟:

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

Alternatively, eager-load the properties with Include or you can even explicitly load them with Load . 另外,可以通过Include急于加载属性,甚至可以通过Load显式加载它们。

For more information, see https://msdn.microsoft.com/en-us/data/jj574232.aspx 有关更多信息,请参见https://msdn.microsoft.com/zh-cn/data/jj574232.aspx

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM