如何使用实体框架从具有一对多关系的两个表中选择所有相关数据

本文关键字:两个 选择 数据 框架 实体 何使用 一对多 关系 | 更新日期: 2023-09-27 17:52:39

我正在与实体框架作斗争,因为我想从item表和其他两个表Label和ItemLabel中选择与一个项目相关的所有内容。Item和ItemLabel表之间的关系是一对多。

我想写IEnumberable List方法,它将检索与项目相关的所有数据。但是,我不知道如何检索ItemLabel表中的所有数据。

这是我的schema:

Item Table: ItemId, Title, Description
Label Table: LabelId, Title
ItemLabel Table: ItemLabelId, ItemId, LabelId, Description
这是我的Item类在数据访问层
public int ItemId { get; set; }
public string Title { get; set; }
public string Description { get; set; }
public IEnumerable<Item> GetItems(Item itemObj)
    {
        List<Item> itemList = new List<Item>();
        using (TestEntities context = new TestEntities())
        {
            itemList = (from item in context.T_Item
                        select new Item()
                        {
                            ItemId = item.IdeaId,
                            Title = item.Title,
                            Description = item.Description,
                            Labels = item.T_ItemLabel.FirstOrDefault(), <<<<<< Error
                        }).ToList();
        }
        return itemList;
    }

请注意,我使用数据库第一的方法。

所以你能告诉我怎样才能得到我在item表中与每个项目相关的所有标签吗?我错过什么了吗?

如何使用实体框架从具有一对多关系的两个表中选择所有相关数据

如果你选择一个实体类型,你可以直接选择它——你不需要像你这样构造一个对象。最简单的是var itemList = content.T_item,因为DbSet也是一个IEnumerable,但以下任何一个都可以工作:

var itemList = (from item in context.T_Item select item);
var itemList = context.T_item.Select(item => item);

您可以通过使用导航属性:var labels = itemList.First().Labels来访问每个Item上的Labels。集合是惰性加载的,因此这涉及到对数据库的另一次访问。将.Include("T_ItemLabel")添加到context.T_item中以获取原始查询中的所有Labels