I am stuck trying to get my model populated given the domain table structure.
I have a main table that stores Vendors and each Vendor can select one-to-many categories from a master category lookup table. The vendor selections are stored in another table that only stores the VendorID and CategoryID to link between them.
I can write the query (below) to include the category table but then I can only display the categoryID and not the category names.
public VendorProfile GetVendor(String id)
{
Guid pid = Guid.Parse(id);
var view = _db.VendorProfiles.Include("VendorCategories").Single(v => v.ProfileID == pid);
return view;
}
I attempted to include the lookup table in the query (below) but this is generating a runtime error.
public VendorProfile GetVendor(String id)
{
Guid pid = Guid.Parse(id);
var view = _db.VendorProfiles.Include("VendorCategories").Include("ProductServiceCategory").Single(v => v.ProfileID == pid);
return view;
}
A specified Include path is not valid. The EntityType ‘VendorProfilesIntranet.VendorProfile’ does not declare a navigation property with the name ‘ProductServiceCategory’.
The Category table does have the navigation property. I don’t know how to add this same navigation property to the main table since it does not have any FK to the lookup table.
UPDATE:
@Gert This notation does work!
_db.VendorProfiles.Include("VendorCategories.ProductServiceCategory").Single(v => v.ProfileID == pid);
However, what I get displayed now is only the category items that were selected. I wish to get the entire list of catgories and have the ones checked that were selected. I am using a scrolling CheckboxList.
<div class="scroll_checkboxes">
<ul>
@foreach (var c in Model.VendorCategories)
{
<li>
<input type="checkbox" name="categories" value="@c.ID" /> @c.ProductServiceCategory.CategoryName
</li>
}
</ul>
@Html.ValidationMessage("Please check at least one Product/Service category")
</div>
UPDATE2:
There might be a better solution but for anyone stuck with similar situation, this worked
<div class="scroll_checkboxes">
<ul>
@foreach (var c in ViewBag.Categories)
{
<li>
@foreach(var vc in Model.VendorCategories)
{
if(c.Id == vc.CategoryID)
{
<input type="checkbox" name="categories" checked="checked" value="@c.Id" /> @vc.ProductServiceCategory.CategoryName
<br />
}
else
{
<input type="checkbox" name="categories" value="@c.Id" /> @vc.ProductServiceCategory.CategoryName
<br />
}
}
</li>
}
</ul>
@Html.ValidationMessage("Please check at least one Product/Service category")
</div>
You can do
to include both the
VendorCategoriesand theirProductServiceCategorys in the result set.By the way, if you use
DbExtensions.Includeyou have intellisense to help you find the right include paths.