Bassie
Bassie

Reputation: 10380

How to properly configure lazy loading

In the view model below, I can see that part.CountryCode is always null.

I can get the data if I use db.Parts.Include(p => p.CountryCode), but I would like to set up lazy loading for now. Does anyone know what I'm missing?

I'm using:

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

Upvotes: 0

Views: 271

Answers (1)

Brad M
Brad M

Reputation: 7898

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

The using block disposes your dbContext once it finishes loading your parts. Lazy-loading requires the dbContext to still be alive.

Upvotes: 1

Related Questions