Can't show the name from binded/relationship model in asp.core

asp.net-core entity-framework-core foreign-keys razor

Question

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:

  • item.Pharmacy
  • item.Pharmacy.PharmacyID (but i want print the name)

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 !

1
0
1/10/2019 8:31:23 AM

Accepted Answer

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();
    }
1
1/11/2019 6:30:30 AM


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