following my previous question (asp.net core creating/updating a foreignkey), I want to display the name of the pharmacy from my Todo model. The following code are actually used:
public class Todo
{
public Pharmacy Pharmacy { get; set; }
}
public class Pharmacy
{
[Key]
public int PharmacyID { get; set; }
public string Name { get; set; }
}
the connector for my selectbox into my create/edit form:
public class PharmacynamePageModel : PageModel
{
[BindProperty]
public int SelectedPharmacy { get; set; }
public SelectList PharmacyNameSL { get; set; }
public void PopulatePharmacysDropDownList(ApplicationDbContext _context, object selectedPharmacy = null)
{
var query = (from p in _context.Pharmacy orderby p.Name select p).ToList();
PharmacyNameSL = new SelectList(query, "PharmacyID", "Name", selectedPharmacy);
}
}
and into my list (index.cshtml):
@foreach (var item in Model.Todo)
{
<tr>
<td>
@Html.DisplayFor(modelItem => item.OwnerID)
</td>
<td>
@Html.DisplayFor(modelItem => item.Pharmacy.Name)
</td>
}
I tried without succes the following variant:
I controlled with SQLServer Management Studio, and My column "PharmacyID" contains value after creating or editing data.
Hope you can help me ;)
Thanks per advance !
Entity Framework Core allows you to use the navigation properties in your model to load related entities. Check if you use the Include
method to specify related data to be included in query results like the sample below
public async Task OnGetAsync()
{
Todo = await _context.Todo
.Include(t => t.Pharmacy).ToListAsync();
}