簡體   English   中英

如何在 ASP.net 核心 API C# 中返回具有存儲庫模式的自我父子?

[英]How to return self parent and child with repository pattern in ASP net core API C#?

我的問題 我有一個名為 category 的表,該表有此列 { ID, ParentId, name }。 ParentId 是相同的 Id,作為此表的示例:

ID 父母身份 名稱
1個 NULL 移動的
2個 1個 蘋果手機
3個 1個 Android
4個 2個 飾品

像那樣,我需要使用 .net core ape 中的通用存儲庫模式返回數據,例如:

ID 名稱 父母名字
2個 IPhone 移動的
3個 IPhone 移動的
4個 配件 蘋果手機

使用通用存儲庫,您只能進行連接,除非您更改通用存儲庫 class 中代碼的實現。

我的建議是將所有數據最初放在一個變量中,然后對其進行操作以獲得所需的結果,如下所示:

var data = categoryRepository.GetAll();
List<CategoryVM> result = new List<CategoryVM>();
foreach(var item in data)
{
    if(item.ParentId != null)
    { 
        var parent = data.Where(x=>x.Id == item.ParentId).First();
        result.Add(new CategoryVM()
        {
             Name = item.Name,
             Id = item.Id,
             ParentName = parent.Name
        };
     }
 }
return Result;

記住要有一個名稱為 CategoryVM 的視圖模型,其中包含最終結果列表中的那些屬性。

暫無
暫無

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

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