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