asp.net 如何使用Entity Framework从两个具有一对多关系的表中选择所有相关数据?

deyfvvtc  于 5个月前  发布在  .NET
关注(0)|答案(1)|浏览(46)

我正在与Entity Framework作斗争,因为我想从Item表和其他两个表LabelItemLabel中选择与一个项目相关的所有内容。ItemItemLabel表之间的关系是一对多。
我想写一个IEEE802.1方法来检索与一个项目相关的所有数据。但是,我不知道如何检索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表?我错过了什么?

pb3skfrl

pb3skfrl1#

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

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

相关问题