如何将其他表加入到我的 LINQ 语句中并 jget 选定的列?

How can I join in other tables to my LINQ statement and jget selected columns?

我创建了这个 linq 语句来获取 AdminTestQuestions 列表:

var adminTests = await db.AdminTests
        .Include(t => t.AdminTestQuestions)
        .Where(t => t.ExamId == examId || examId == 0)
        .Where(t => t.TestStatusId == testStatusId || testStatusId == 0)
        .ToListAsync();
        return Ok(adminTests);

该语句有效,但我需要在已有的列中再添加两列:

我想做的是也得到

谁能告诉我如何扩展我的 linq 语句来做到这一点。令我困惑的是我如何阻止 linq 获取所有问题和问题 table 列。

CREATE TABLE [dbo].[AdminTest] (
    [AdminTestId]  INT            IDENTITY (1, 1) NOT NULL,
    [Title]        NVARCHAR (100) NOT NULL,

CREATE TABLE [dbo].[AdminTestQuestion]

    [AdminTestQuestionId] INT              IDENTITY (1, 1) NOT NULL,
    [AdminTestId]         INT              NOT NULL,
    [QuestionUId]         UNIQUEIDENTIFIER NOT NULL,

CREATE TABLE [dbo].[Question] (
    [QuestionId]       INT              IDENTITY (1, 1) NOT NULL,
    [ProblemId]        INT              NOT NULL,
    [QuestionUId]      UNIQUEIDENTIFIER DEFAULT (newid()) NOT NULL,
    [Title]            NVARCHAR (100)   NULL,
    [Grade]            INT              NOT NULL,

CREATE TABLE [dbo].[Problem] (
    [ProblemId]       INT             IDENTITY (1, 1) NOT NULL,
    [SubTopicId]      INT             NOT NULL,
    [Title]           NVARCHAR(20)    NULL

您可以采取的一种方法是在 return 之前将您的 AdminTest 扁平化为 DTO 对象。这使您可以明确控制数据的结构以及哪些列可见。

首先你需要 class:

public class AdminTestDto 
{
    public int AdminTestId { get; set; }
    public string Title { get; set; }
    public int AdminTestQuestionId { get; set; }
    public int QuestionUId { get; set; }
    public string QuestionTitle { get; set; }
    public int SubTopicId { get; set; }

    public AdminTestDto(AdminTest a)
    {
        this.AdminTestId = a.AdminTestId;
        this.Title = a.Title;
        this.AdminTestQuestionId = a.AdminTestQuestion.AdminTestQuestionId;
        this.QuestionUId = a.AdminTestQuestion.QuestionUId;
        this.QuestionTitle = a.AdminTestQuestion.Question.Title;
        this.SubTopicId = a.AdminTestQuestion.Question.Problem.SubTopicId;
    }
}

然后在您的 LINQ 中:

var adminTests = await db.AdminTests
    .Include(t => t.AdminTestQuestions)
    .Where(t => t.ExamId == examId || examId == 0)
    .Where(t => t.TestStatusId == testStatusId || testStatusId == 0)
    .Select(t => new AdminTestDto(t))
    .ToListAsync();
    return Ok(adminTests);