我有以下表格,我想用EF 4.1 Code First映射:
项目 - 可以包含多个类别的项目
ItemCategories - 用于映射项目的多对多关系的关系表< - > Categories
类别 - 类别,类别是类别树,ParentId是自引用
CategoryLink - 此表包含树的边缘
问题是我如何为我的实体类创建EF代码的第一个映射,以便我可以在Item上使用Categories集合属性,同时能够在查询中使用我的所有表(尤其是关系表上的连接)像这样:
//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;
以下是具有DbContext(没有映射)的实体类
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; }
}
由于
答案 0 :(得分:0)
我只是玩了一些代码,首先不确定这是否有帮助。但是下面的帖子展示了如何创建桥接表并首先解决EF4.1代码中的多对多问题。
How to perform CRUD with Entity Framework Code-First?
也 Forcing a bridge/join table to become a many to many relationship in EF4