我有一个EF7 Code第一个模型设置如下:
public class Employee
{
public Guid Id { get; set; }
public string FullName { get; set; }
public Guid DepartmentId { get; set; }
public Department Department { get; set; }
}
public class Department
{
public Guid Id { get; set; }
public string Department{ get; set; }
public List<Employee> Employees { get; set; }
}
尝试通过API调用检索所有Employees时:
[HttpGet("")]
public JsonResult GetAll()
{
try
{
var employees= _repository.GetAllEmployees();
var results = Mapper.Map<IEnumerable<EmployeeViewModel>(employees);
Response.StatusCode = (int)HttpStatusCode.OK;
return Json(results);
}
catch (Exception ex)
{
Response.StatusCode = (int)HttpStatusCode.BadRequest;
return Json(new { Message = ex.Message });
}
}
我收到部门的空白。
存储库方法如下所示:
public IEnumerable<Post> GetAllEmployees()
{
try
{
return _context.Employees
.Include(e => e.Department)
.ToList();
}
catch (Exception ex)
{
return null;
}
}
我做错了什么?我知道这一定很简单。
谢谢你的帮助。
更新:我正在正确播种初始数据。
SQL Generated如下:
'SELECT [e].[Id], [e].[DepartmentId], [e].[FullName], [d].[Id], [d].[Department] FROM [Employee] AS [e] INNER JOIN [Department] AS [d] ON [e].[DepartmentId] = [d].[Id]'
但我现在看到以下错误:
Newtonsoft.Json.JsonSerializationException: Self referencing loop detected for property 'Department' with type 'Project.Models.Department'. Path '[0].Department.Employees[0]