【问题标题】:How to properly configure lazy loading如何正确配置延迟加载
【发布时间】:2018-11-24 14:07:18
【问题描述】:

在下面的视图模型中,我可以看到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

视图模型

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

【问题讨论】:

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


    【解决方案1】:
    using (var db = new ApplicationDbContext())
    {
        return db.Parts.ToList();
    }
    

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

    【讨论】:

    • 感谢布拉德,这是有道理的 - 我不知道它会这样工作。你会建议 Commands 实现 IDisposable 以便我可以将 GetParts() 包装在 using Commands() 中吗?
    • 就我个人而言,我建议您提前包含您需要的任何导航属性。我建议使用依赖注入并让您的类接受 dbContext 的实例,然后将 dbContext 的生命周期限定为请求的生命周期(我不确定它如何与 WPF 一起工作,但 dbContext 生命周期不应该是责任您的 NetStandard 库)
    • 我想尝试一下,但我不确定如何将 .net-core DbContext 注入 .net-framework 应用程序
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-10-25
    • 1970-01-01
    • 1970-01-01
    • 2011-08-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多