EF代码优先。相关实体未加载
EF Code First. Related Entity is not loading
我有 Entity Framework 个代码优先实体:
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();
问题是,当我加载客户时,他的所有帐户也都加载了,但他们的服务设置为空。为什么没有加载?
提前致谢
延迟加载相关实体需要框架创建实体的代理。尝试将您的导航属性虚拟化:
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
您需要加载实体。根据您的评论:
IQueryable<Customer> customers = Customers.Include(x => x.Accounts.Select(y => y.Service));
如果您想要延迟加载的代理,它们也应该是 virtual
...但是对于预加载,则没有必要
我有 Entity Framework 个代码优先实体:
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();
问题是,当我加载客户时,他的所有帐户也都加载了,但他们的服务设置为空。为什么没有加载?
提前致谢
延迟加载相关实体需要框架创建实体的代理。尝试将您的导航属性虚拟化:
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
您需要加载实体。根据您的评论:
IQueryable<Customer> customers = Customers.Include(x => x.Accounts.Select(y => y.Service));
如果您想要延迟加载的代理,它们也应该是 virtual
...但是对于预加载,则没有必要