【发布时间】:2021-06-13 01:05:14
【问题描述】:
我正在尝试从五个表中获取数据:Category - subCategory - secondSubCategory - type - heat 这些都与主表(属性)相关。
表 (category - subCategory - secondSubCategory) 像层一样相关 (Category => subCategory => secondSubCategory)
我试图通过以下方式获取数据:
public IActionResult getAllProperties()
{
var properties = db.properties
.Include(cat => cat.category)
.Include(sub => sub.subCategory)
.Include(sec => sec.SecondSubCategory)
.Include(e => e.heating)
.Include(e => e.type)
.OrderByDescending(x => x.id)
.ToList();
return Ok(properties);
}
但返回的数据包含类型和加热字段的值,但 (categoryId 和 subCategoryId 和 secondSubCategoryId) 的值为空值,知道这些字段具有值
属性.cs
public class Property
{
[Key]
public int id { get; set; }
public int typeId { get; set; }
public type type { get; set; }
public int heatingId { get; set; }
public heating heating { get; set; }
public int? categoryId { get; set; }
public category category { get; set; }
public int? subCategoryId { get; set; }
public subCategory subCategory { get; set; }
public int? secondSubCategoryId { get; set; }
public SecondSubCategory SecondSubCategory { get; set; }
}
响应不包括 category 和 subCategory 和 secondSubCategory :
{
"id": 14,
"typeId": 1,
"type": {
"id": 1,
"typeName": "Flat"
},
"heatingId": 4,
"heating": {
"id": 4,
"heatingName": "Conditioning"
},
"categoryId": 1,
"category": null,
"subCategoryId": 2,
"subCategory": null,
"secondSubCategoryId": 3,
"secondSubCategory": null
}
响应包括类别和子类别以及第二个子类别:
{
"id": 14,
"typeId": 1,
"type": {
"id": 1,
"typeName": "Flat"
},
"heatingId": 4,
"heating": {
"id": 4,
"heatingName": "Conditioning"
},
"categoryId": null,
"category": null,
"subCategoryId": null,
"subCategory": null,
"secondSubCategoryId": null,
"secondSubCategory": null
}
Category.cs
public class category
{
public int id { get; set; }
public string category_Name { get; set; }
public IList<subCategory> subCategories { get; set; }
public Property Property { get; set; }
}
subCategory.cs:
public class subCategory
{
public int id { get; set; }
public string subCategoryName { get; set; }
public int CategoryId { get; set; }
public category category { get; set; }
public IList<SecondSubCategory> secondSubCategories { get; set; }
public Property Property { get; set; }
}
secondSubCategory.cs:
public class SecondSubCategory
{
public int id { get; set; }
public string subCategoryName { get; set; }
public int subCategoryId { get; set; }
public subCategory subCategory { get; set; }
public Property Property { get; set; }
}
【问题讨论】:
-
查询中
.Include(cat=>cat.category)的目的是什么? -
你能显示类别或子类别类
-
@atiyar 目的是从与属性相关的类别中获取数据
-
但是你已经有
.Include(s=>s.category)了。 -
@Sergey
public class category { public int id { get; set; } public string category_Name { get; set; } public IList<subCategory> subCategories { get; set; } public Property Property { get; set; } }
标签: c# entity-framework-core asp.net-core-webapi