如何正确配置延迟加载

How to properly configure lazy loading

在下面的视图模型中,我可以看到 part.CountryCode 始终是 null

如果我使用db.Parts.Include(p => p.CountryCode),我可以获取数据,但我现在想设置延迟加载。有谁知道我错过了什么?

我正在使用:

ViewModel

class PagePartsViewModel : BaseViewModel
{
    public ObservableCollection<PartViewModel> Parts { get; set; }

    public PagePartsViewModel()
    {
        Parts = new ObservableCollection<PartViewModel>();
        var parts = StandardDatabase.Commands.GetParts();
        foreach (var part in parts)
        {
            Parts.Add(new PartViewModel(part));
        }
    }
}

GetParts()

public static List<Part> GetParts()
{
    using (var db = new ApplicationDbContext())
    {
        return db.Parts.ToList();
    }
}

ApplicationDbContext.OnConfiguring()

optionsBuilder
    .UseLazyLoadingProxies()
    .UseSqlServer("Connection String");

ApplicationDbContext.OnModelCreating()

builder.Entity<Part>()
    .HasOne(p => p.CountryCode);
builder.Entity<CountryCode>()
    .HasAlternateKey(cc => cc.Code);

Part.cs

public class Part : EntityBase
{
    public string OEMNumber { get; set; }
    public string Description { get; set; }
    public string CountryOfOrigin { get; set; }
    [Column(TypeName = "decimal(10, 2)")]
    public decimal BellUnitCost { get; set; }
    [Column(TypeName = "decimal(9, 3)")]
    public double Weight { get; set; }

    public virtual StockQuantity StockQuantity { get; set; }
    public virtual ICollection<PartQuantity> PartQuantities { get; set; }

    public virtual CountryCode CountryCode { get; set; }
}

CountryCode.cs

public class CountryCode : EntityBase
{
    public string Code { get; set; }
    public string FriendlyName { get; set; }

    public virtual ICollection<Part> Parts { get; set; }
}
using (var db = new ApplicationDbContext())
{
    return db.Parts.ToList();
}

using 块在完成加载您的部件后处理您的 dbContext。延迟加载需要 dbContext 仍然存在。