如何返回 EF Core 中的模型列表以及 SQL Server 中的两个相关列

问题描述 投票:0回答:1

我试图在

usersanctions
表中获取学生制裁列表,它有两个相关的列:
StudentId
SanctionId

我的

StudentModel
班级:

public class StudentModel
{
    public int StudentId {  get; set; }
    public List<UserSanctionModel> Sanctions { get; set; } = new List<UserSanctionModel>();
}

UserSanctionModel
有两个相关的栏目

public class UserSanctionModel
{
    public int UserSanctionId { get; set; }
    public int SanctionId { get; set; }
    public int StudentId { get; set; }
    public SanctionModel Sanction { get; set; } = new();
}

最后是

SanctionModel

public class SanctionModel
{
    public int SanctionId { get; set; }
    public string SanctionName { get; set; } = string.Empty;
}

下面是我的 EF

include
,我以为它会得到制裁列表,因为它有一列
StudentId
SanctionId

public async Task<ActionResult<IEnumerable<StudentModel>>> GetStudents(FilterParameter param)
{
    return await _context.Students
                         .Include(us => us.Sanctions)
                         .ThenInclude(s => s.Sanction)
}

我想知道为什么 EF 在我的数据库中创建一个新列:

SELECT 
    [s].[StudentId], [s].[CourseId], [s].[DepartmentId], 
    [s].[SectionId], [s].[StudentName], [s].[YearLevel], 
    [c].[CourseId], [c].[CourseName], [c].[ShortcutName], 
    [d].[DepartmentId], [d].[DepartmentName], [s0].[SectionId], 
    [t].[UserSanctionId], [t].[SanctionId], [t].[StudentId], 
    [t].[StudentModelStudentId], [t].[SanctionId0], 
    [t].[SanctionName], [s0].[SectionName]
FROM 
    [Students] AS [s]
INNER JOIN 
    [Courses] AS [c] ON [s].[CourseId] = [c].[CourseId]
INNER JOIN 
    [Departments] AS [d] ON [s].[DepartmentId] = [d].[DepartmentId]
INNER JOIN 
    [Sections] AS [s0] ON [s].[SectionId] = [s0].[SectionId]
LEFT JOIN 
    (SELECT [u].[UserSanctionId], [u].[SanctionId], [u].[StudentId], [u].[StudentModelStudentId], [s1].[SanctionId] AS [SanctionId0], [s1].[SanctionName]
      FROM [UserSanctions] AS [u]
      INNER JOIN [Sanctions] AS [s1] ON [u].[SanctionId] = [s1].[SanctionId]
  ) AS [t] ON [s].[StudentId] = [t].[StudentModelStudentId] //I gues this line
  ORDER BY [s].[StudentId], [c].[CourseId], [d].[DepartmentId], [s0].[SectionId], [t].[UserSanctionId]

这是

StudentModelStudentId
栏,应该是
StudentId

.net sql-server entity-framework asp.net-core entity-framework-migrations
1个回答
0
投票

所以我在互联网上找到了这个线程,它说我们需要在属性和模型中分配外键

public class UserSanctionModel
{
  public int UserSanctionId { get; set; }
  public int SanctionId { get; set; }
  public SanctionModel Sanction { get; set; } = new();

  //This fixed my migrations and query
  public int StudentId { get; set; }
  [ForeignKey("StudentId")]
  public StudentModel Student { get; set; }
}
© www.soinside.com 2019 - 2024. All rights reserved.