创建了一个与另一个表具有多对多关系的表,并在中间表的基础上要获取另一个表的名称。
以下是表格结构:
学校:
public partial class Schools
{
public Guid ID { get; set; }
public string Name{ get; set; }
// Navigation
public ICollection<SchoolsSchoolType> SchoolsSchoolTypes { get; set; }
}
SchoolType:
public class SchoolType
{
public Guid Id { get; set; }
public string Name { get; set; }
//Navigation
public ICollection<SchoolsSchoolType> SchoolsSchoolTypes { get; set; }
}
SchoolsSchoolType(它是中间表)
public class SchoolsSchoolType
{
public Guid Id { get; set; }
public Guid ShoolId { get; set; }
public Schools Schools { get; set; }
public Guid SchoolTypeId { get; set; }
public SchoolType SchoolType { get; set; }
}
现在调用存储库中的表:
public async Task<IEnumerable<Schools>> GetSchoolBySchoolId(Guid schoolId)
{
List<Schools> schools = null;
schools = await _GpsContext.School.AsNoTracking().Where(x => x.ID == schoolId)
.Include(sst => sst.SchoolsSchoolTypes)
.ThenInclude(st=>st.SchoolType).ToListAsync();
return schools;
}
在控制器代码中如下:
public async Task<IActionResult> GetforUpdateSchool(string schoolId)
{
var schools = await _schoolsRepository.GetSchoolBySchoolId(Guid.Parse(schoolId));
List<SchoolUpdateBySchoolIdVm> schoolUpdateBySchoolIdVms = new List<SchoolUpdateBySchoolIdVm>();
foreach (Schools school in schools)
{
schoolUpdateBySchoolIdVms.Add(new SchoolUpdateBySchoolIdVm
{
id = school.ID.ToString(),
name = school.Name,
schooltypeId = school.SchoolsSchoolTypes.Select(s => s.SchoolType.Id).ToString()
}); ;
}
return Ok(schoolUpdateBySchoolIdVms);
}
但是在这里,输出给出了JSON错误。
[
{
"id": "1cb0cd54-13e1-465a-8c1a-4699884f4c4c",
"name": "Angela High School",
"schooltypeId": "System.Linq.Enumerable+SelectEnumerableIterator`2[DataLibrary.Data.SchoolModel.SchoolsSchoolType,System.Guid]" // Here is problem, want to get Id and name.
}
]
答案 0 :(得分:0)
这行是错误的
schooltypeId = school.SchoolsSchoolTypes.Select(s => s.SchoolType.Id).ToString()
您有多个SchoolsSchoolTypes
,因此,如果您希望将其作为字符串,请替换为以下
schooltypeId = String.Join(',', school.SchoolsSchoolTypes.Select(s => s.SchoolType.Id.ToString()))
这会将它们转换为逗号分隔的值