簡體   English   中英

如何使用Entity Framework從具有一對多關系的兩個表中選擇所有相關數據?

[英]How to select all related data from two tables having one-to-many relationship using Entity Framework?

我正在努力與Entity Framework一起工作,因為我想從Item表中選擇與一項相關的所有內容,而在另兩個表中選擇Label和ItemLabel。 Item和ItemLabel表之間的關系是一對多的。

我想編寫IEnumberable List方法,該方法將檢索與項目相關的所有數據。 但是,我不知道如何檢索ItemLabel表中的所有數據。

這是我的架構:

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;

    }

請注意,我正在使用數據庫優先方法。

那么, 能否請您告訴我如何獲得與項目表中每個項目相關的所有標簽? 我有什么想念的嗎?

如果要選擇實體類型,則只需選擇它-不必像正在構造的那樣構造對象。 最簡單的是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);

然后,您只需使用導航屬性即可訪問每個Item上的Labelsvar labels = itemList.First().Labels 集合是延遲加載的,因此這涉及到數據庫的另一次訪問。 .Include("T_ItemLabel")添加到context.T_item以獲取原始查詢中的所有Labels

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM