Создана таблица со многими ко многим отношениями с другим, и на основе промежуточной таблицы нужно получить имя поля другого.
Ниже приведена структура таблицы:
School:
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.
}
]