[英]How to select all related data from two tables having one-to-many relationship using Entity Framework?
I am struggling with Entity Framework as I would like to select everything related to one item from Item table and the other two tables Label and ItemLabel. 我正在努力与Entity Framework一起工作,因为我想从Item表中选择与一项相关的所有内容,而在另两个表中选择Label和ItemLabel。 The relationship between Item and ItemLabel tables is one to many.
Item和ItemLabel表之间的关系是一对多的。
I would like to write IEnumberable List method that will retrieve all the data related to an item. 我想编写IEnumberable List方法,该方法将检索与项目相关的所有数据。 However, I don't know how to retrieve the all the data in the ItemLabel table.
但是,我不知道如何检索ItemLabel表中的所有数据。
Here's my schema: 这是我的架构:
Item Table: ItemId, Title, Description
Label Table: LabelId, Title
ItemLabel Table: ItemLabelId, ItemId, LabelId, Description
and here's my Item class in the Data Access Layer 这是我在数据访问层中的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;
}
Please note that I am using Database First approach. 请注意,我正在使用数据库优先方法。
So could you please tell me how can I get all the labels related to each item I have in the Item table? 那么, 能否请您告诉我如何获得与项目表中每个项目相关的所有标签? Am I missing anything?
我有什么想念的吗?
If you're selecting an entity type, you can just select it - you don't have to construct an object like you're doing. 如果要选择实体类型,则只需选择它-不必像正在构造的那样构造对象。 Simplest is
var itemList = content.T_item
because DbSet is also an IEnumerable but either of the following will work: 最简单的是
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);
You can then access the Labels
on each Item
by just using the navigation property: var labels = itemList.First().Labels
. 然后,您只需使用导航属性即可访问每个
Item
上的Labels
: var labels = itemList.First().Labels
。 The collections are lazy-loaded, so this involves another trip to the database. 集合是延迟加载的,因此这涉及到数据库的另一次访问。 Add
.Include("T_ItemLabel")
to the context.T_item
to fetch all the Labels
in the original query. 将
.Include("T_ItemLabel")
添加到context.T_item
以获取原始查询中的所有Labels
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.