i have the following tables which i want to map with EF 4.1 Code First:
Items - An item which can have a number of categories
ItemCategories - The relation table to map the many-to-many relationship of Items<->Categories
Category - An Category, categories are a tree of categories, ParentId is self referencing
CategoryLink - This table contains the edges of the tree
The question is how can I create the EF code first mapping for my entity classes so that I can use the Categories collection property on Item while being able to use all my tables inside a query (especially a join over the relation table) like this:
//searchIds contains a list of category guids to be searched for inside the category tree
var query = from item in db.Items
join itemCategory in db.ItemCategories on item.Id equals itemCategory.ItemId
join category in db.Categories on itemCategory.CategoryId equals category.Id
join categoryLink in db.CategoryLinks on category.Id equals categoryLink.ChildId
where searchIds.Contains(categoryLink.ParentId)
select item;
Here are the entity classes with DbContext(with开发者_JS百科out the mappings)
class TestContext : DbContext
{
public DbSet<Category> Categories { get; set; }
public DbSet<Item> Items { get; set; }
public DbSet<ItemCategory> ItemCategories { get; set; }
public DbSet<CategoryLink> CategoryLinks { get; set; }
}
public class Item
{
public Guid Id { get; set; }
public string Name { get; set; }
public virtual ICollection<Category> Categories { get; set; }
}
public class ItemCategory
{
public Guid ItemId { get; set; }
public Guid CategoryId { get; set; }
}
public class Category
{
public Guid Id { get; set; }
public Guid? ParentId { get; set; }
public virtual Category Parent { get; set; }
public string Name { get; set; }
}
public class CategoryLink
{
public Guid ParentId { get; set; }
public Guid ChildId { get; set; }
public virtual Category Parent { get; set; }
public virtual Category Child { get; set; }
}
Thanks
I've only played around a bit with code first not sure if this may help. but the below posts show how to create bridge tables and work around for many-to-many issue with EF4.1 code first.
How to perform CRUD with Entity Framework Code-First?
also Forcing a bridge/join table to become a many to many relationship in EF4
精彩评论