How to asynchronously call a relation when lazy loading with Entity Framework 6.4?

async-await c# entity-framework entity-framework-6 lazy-loading

Question

I have a project that used Entity-Framework 6.4 to access data from the database.

I have the following model

public class Product
{
    public int Id { get; set; }
    public string Title { get; set; }
    public bool Available { get; set; }
    // ...
    public int CategoryId { get; set; }
    public virtual Category Category { get; set; }
}

In the controller, I want to access the Category using lazy loading. I know I can use Include() extension to eager load the relation. But instead, I want to lazy load it. Here is an example of how I would like to use it

public async Task<ActionResult> Get(ShowProduct vm)
{
    if (ModelState.IsValid)
    {
        using (var db = new DbContext())
        {
            Product model = await db.Products.FirstAsync(vm.Id);

            vm.Title = model.Title;

            if (model.Avilable)
            {
                // How can call the **Category** property using await operator?
                vm.CategoryTitle = model.Category.Title;
            }
        }
    }

    return View(vm);
}

How can I lazy load the Category relation using await operator to prevent locking the current thread?

1
2
4/2/2020 4:16:48 PM

Popular Answer

How can I lazy load the Category relation using await operator to prevent locking the current thread?

You must explicitly load the reference if you want async.

Etither

await db.Entry(model).Reference<Category>().LoadAsync();

Or, fetch the related entity explicitly, and let the Change Tracker fix-up the navigation property.

var category = await db.Categories.FindAsync(model.CategoryId);
vm.CategoryTitle = model.Category.Title;
2
4/2/2020 4:22:32 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow