我在做一个项目,我需要使用延迟加载我安装了包和配置,查询工作但关系列返回空值。如何使用延迟加载?
已安装 Microsoft.EntityFrameworkCore.Proxies(版本 5.0.7)
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
if (!optionsBuilder.IsConfigured)
{
optionsBuilder.UseSqlServer("ConnectionString");
optionsBuilder.UseLazyLoadingProxies(true);
}
}
我的模型(我用 DB First 制作)
public partial class Customer
{
public Customer()
{
Orders = new HashSet<Order>();
}
public int CustomerId { get; set; }
public int? CompanyId { get; set; }
public string Name { get; set; }
public string LastName { get; set; }
public string FullName { get; set; }
public string Phone { get; set; }
public string Mail { get; set; }
virtual public Company Company { get; set; }
virtual public ICollection<Order> Orders { get; set; }
}
public partial class Company
{
public Company()
{
Customers = new HashSet<Customer>();
}
public int CompanyId { get; set; }
public string Name { get; set; }
public string TaxNumber { get; set; }
public virtual ICollection<Customer> Customers { get; set; }
}
使用的方法:
public List<Customer> GetCustomers()
{
using (dbContext context = new dbContext())
{
return context.Customers.ToList();
}
}
答案 0 :(得分:1)
根据documentation,延迟加载应该这样实现
也安装 Microsoft.EntityFrameworkCore.Abstractions
包并更改实现:
public partial class Customer
{
private ICollection<Orders> _orders;
public Customer()
{
Orders = new HashSet<Order>();
}
public Customer(ILazyLoader lazyLoader)
{
LazyLoader = lazyLoader;
}
private ILazyLoader LazyLoader { get; set; }
public int CustomerId { get; set; }
public int? CompanyId { get; set; }
public string Name { get; set; }
public string LastName { get; set; }
public string FullName { get; set; }
public string Phone { get; set; }
public string Mail { get; set; }
virtual public Company Company { get; set; }
public ICollection<Order> Orders
{
get => LazyLoader.Load(this, ref _orders);
set => _orders = value;
}
}
在对订单进行迭代后,将获取数据
using(var db = new YourContext())
{
var customers = db.Customers.ToList();
foreach(var customer in customers )
{
Console.WriteLine($"Customer: {customer.Name} {customer .LastName}");
foreach(var order in customer.Ortders) // lazy loading initiated
{
Console.WriteLine($"\t{order.Id}");
}
}
}