[英]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 ![]() |
ParentId![]() |
Name![]() |
---|---|---|
1 ![]() |
NULL ![]() |
Mobile![]() |
2 ![]() |
1 ![]() |
IPhone![]() |
3 ![]() |
1 ![]() |
Android ![]() |
4 ![]() |
2 ![]() |
Accessorice![]() |
Like that, I need to return data using generic repository pattern in.net core ape like:像那样,我需要使用 .net core ape 中的通用存储库模式返回数据,例如:
ID ![]() |
NAme![]() |
ParentName![]() |
---|---|---|
2 ![]() |
Iphone ![]() |
Mobile![]() |
3 ![]() |
Iphone ![]() |
Mobile![]() |
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.