简体   繁体   English

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

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

My Question .我的问题 I have a table called category, this table had this column { ID, ParentId, name }.我有一个名为 category 的表,该表有此列 { ID, ParentId, name }。 The ParentId is the same Id, as an example for this table: ParentId 是相同的 Id,作为此表的示例:

Id ID ParentId父母身份 Name名称
1 1个 NULL NULL Mobile移动的
2 2个 1 1个 IPhone苹果手机
3 3个 1 1个 Android Android
4 4个 2 2个 Accessorice饰品

Like that, I need to return data using generic repository pattern in.net core ape like:像那样,我需要使用 .net core ape 中的通用存储库模式返回数据,例如:

ID ID NAme名称 ParentName父母名字
2 2个 Iphone IPhone Mobile移动的
3 3个 Iphone IPhone Mobile移动的
4 4个 Accessories配件 iPhone苹果手机

Using generic repository you are limited in doing joins, unless you change the implementation of your code in generic repository class.使用通用存储库,您只能进行连接,除非您更改通用存储库 class 中代码的实现。

My advice is to get all of data initially in a variable and then manipulate it to get your required result, something like this:我的建议是将所有数据最初放在一个变量中,然后对其进行操作以获得所需的结果,如下所示:

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;

Remember to have a viewmodel with the name of CategoryVM where you have those properties that are in your final resultant list.记住要有一个名称为 CategoryVM 的视图模型,其中包含最终结果列表中的那些属性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 asp.net core C# 如何在存储库模式中传递值 - asp.net core C# how can I pass value in a repository pattern C#从asp.net Web API返回父子JSON对象? - C# return a parent child JSON object from the asp.net web api? 自引用对象的有序树的设计模式(C#/ ASP.Net Core / EFCore) - Design pattern for self-referencing ordered tree of objects (C#/ASP.Net Core/EFCore) 如何在 ASP.NET 核心中使用存储库模式进行排序? - How to sort using repository pattern in ASP.NET core? 如何在我的 ASP.NET 核心 Web API 项目中使用工作单元模式和通用存储库模式? - How can I use unit of work pattern with generic repository pattern in my ASP.NET Core Web API project? C#asp.net核心v。2自托管如何将图片上传到wwwroot下的子文件夹? - C# asp.net core v. 2 self hosted how to upload image to subfolder under wwwroot? 返回具有子属性 C#、.NET 的父 class - Return parent class with child properties C#, .NET 在C#中以列表为核心的存储库模式 - Repository pattern with list as its core in C# 一个视图中的父子模型(多个模型)(ASP.NET Core(C#)+ MVC +实体框架) - Parent-Child model (multiple model) in one view (ASP.NET Core (C#) + MVC + Entity Framework) ASP .NET Core Webapi父子关系? - ASP .NET Core Webapi Parent - Child relation?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM