如何正确配置延迟加载

时间:2018-11-24 14:07:18

标签: c# .net-core entity-framework-core lazy-loading .net-standard

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

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

我正在使用:

  • Microsoft.EntityFrameworkCore (2.1.4)NETStandard.Library(2.0.3)
  • UI是带有.NET 4.6.1的WPF

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

1 个答案:

答案 0 :(得分:1)

using (var db = new ApplicationDbContext())
{
    return db.Parts.ToList();
}

using块在完成加载部件后立即处理dbContext。延迟加载要求dbContext仍然有效。