I have three tables Exam, Test and UserTest.
CREATE TABLE [dbo].[Exam] (
[ExamId] INT IDENTITY (1, 1) NOT NULL,
[SubjectId] INT NOT NULL,
[Name] NVARCHAR (50) NOT NULL,
[Description] NVARCHAR (MAX) NOT NULL,
CONSTRAINT [PK_Exam] PRIMARY KEY CLUSTERED ([ExamId] ASC),
CONSTRAINT [FK_ExamSubject] FOREIGN KEY ([SubjectId]) REFERENCES [dbo].[Subject] ([SubjectId]),
CONSTRAINT [FK_Exam_ExamType] FOREIGN KEY ([ExamTypeId]) REFERENCES [dbo].[ExamType] ([ExamTypeId])
);
CREATE TABLE [dbo].[Test] (
[TestId] INT IDENTITY (1, 1) NOT NULL,
[ExamId] INT NOT NULL,
[Title] NVARCHAR (100) NULL,
[Status] INT NOT NULL,
[CreatedDate] DATETIME NOT NULL,
CONSTRAINT [PK_Test] PRIMARY KEY CLUSTERED ([TestId] ASC),
CONSTRAINT [FK_TestExam] FOREIGN KEY ([ExamId]) REFERENCES [dbo].[Exam] ([ExamId])
);
CREATE TABLE [dbo].[UserTest] (
[UserTestId] INT IDENTITY (1, 1) NOT NULL,
[UserId] NVARCHAR (128) NOT NULL,
[TestId] INT NOT NULL,
[Result] INT NULL
CONSTRAINT [PK_UserTest] PRIMARY KEY CLUSTERED ([UserTestId] ASC),
CONSTRAINT [FK_UserTestTest] FOREIGN KEY ([TestId]) REFERENCES [dbo].[Test] ([TestId])
);
An exam can have many tests and a user can try any test a number of times.
How can I code a LINQ statement using the extension method syntax that allows me to see the following for UserId == 1 (I assume UserId == 1 in a Where clause) :
Exam Test Title UserTestID UserId Result
1 1 1a 1 1 20
1 1 1a 2 1 30
1 1 1a 3 1 40
1 2 1b 4 1 98
1 3 1c 5 1 44
2 4 2a
2 5 2b 6 1 12
Or if UserId == 2:
Exam Test Title UserTestID UserId Result
1 1 1a 7 2 27
1 2 1b
1 3 1c 8 2 45
2 4 2a
2 5 2b
Or if UserId is null
Exam Test Title UserTestID UserId Result
1 1 1a
1 2 1b
1 3 1c
2 4 2a
2 5 2b
Note this question has undergone a few changes thanks to suggestions I received. Now there is a bounty I hope for a quick answer that I can accept.