I will start by saying this may not be conceptually correct so I will post my problem also, so if someone can help with the underlying problem I won't need to do this.
Here is a simplified version of my model.
public class MenuItem
{
public int MenuItemId { get; set; }
public string Name { get; set; }
public virtual ICollection<Department> Departments { get; set; }
private ICollection<MenuSecurityItem> _menuSecurityItems;
public virtual ICollection<MenuSecurityItem> MenuSecurityItems
{
get { return _menuSecurityItems ?? (_menuSecurityItems = new HashSet<MenuSecurityItem>()); }
set { _menuSecurityItems = value; }
}
}
public class Department
{
public int DepartmentId { get; set; }
public string Name { get; set; }
public virtual ICollection<MenuItem> MenuItems { get; set; }
}
My underlying problem is that I want to select all MenuItems that belong to a Department (Department with DepartmentId = 1 for arguments sake) and also include all MenuSecurityItems.
I am unable to Include() the MenuSecurityItems as the MenuItems navigation collection is of type ICollection and doesn't support Include(). This also doesn't seem to work Department.MenuItems.AsQueryable().Include(m => m.MenuSecurityItems)
The way I "fixed" this issue was creating an entity for the many-to-many mapping table Code First creates.
public class DepartmentMenuItems
{
[Key, Column(Order = 0)]
public int Department_DepartmentId { get; set; }
[Key, Column(Order = 1)]
public int MenuItem_MenuItemId { get; set; }
}
I then was able to join through the mapping table like so. (MenuDB being my DBContext)
var query = from mItems in MenuDb.MenuItems
join depmItems in MenuDb.DepartmentMenuItems on mItems.MenuItemId equals depmItems.MenuItem_MenuItemId
join dep in MenuDb.Departments on depmItems.Department_DepartmentId equals dep.DepartmentId
where dep.DepartmentId == 1
select mItems;
This actually worked for that particular query... however it broke my navigation collections. Now EF4.1 is throwing an exception as it is trying to find an object called DepartmentMenuItems1 when trying to use the navigation collections.
If someone could either help me with the original issue or the issue I have now created with the mapping table entity it would be greatly appreciated.