我创建了这个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);
该声明有效,但我需要再添加两列我已经拥有的列:
我想做的是获得
Title
来自的问题
问题表和SubTopidId
有人可以告诉我如何扩展我的linq语句来做到这一点。令我困惑的是我如何阻止linq获取所有问题和问题表列。
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
答案 0 :(得分:0)
您可能采取的一种方法是在返回之前将AdminTests展平为DTO对象。这使您可以明确控制数据的结构以及可见的列。
首先,你需要一个班级:
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);