简体   繁体   中英

How can I add in a couple of additional fields to the lowest level of a Linq query

I have the following Linq Statement:

        db.AdminTests
        .Include(t => t.AdminTestQuestions)
        .ToList();

This gives me a list of AdminTests and in each of these there is a collection with AdminTestQuestions:

public class AdminTest
{
    public AdminTest()
    {
        this.AdminTestQuestions = new List<AdminTestQuestion>();
    }
    public int AdminTestId { get; set; }
    public virtual ICollection<AdminTestQuestion> AdminTestQuestions { get; set; }
}

The data returned in AdminTestQuestions is a collection containing this information:

public partial class AdminTestQuestion
{
    public int AdminTestQuestionId { get; set; }
    public int AdminTestId { get; set; }
    public System.Guid QuestionUId { get; set; }
    public virtual AdminTest AdminTest { get; set; }
    // I would like to add subTopicId here
    // I would like to add title here
}

Is there a way that I could return additional information into this collection? Firstly to do this would I need to add a couple of virtual parameters? Second how/can I do this with LINQ?

Specifically what I would like to do is to add an additional two pieces of data that are based on the QuestionUId. I would like to add "Title" (from the question table) and "SubTopicId" (from the problem table). These can be obtained by somehow joining to the question table and then to the problem table:

public class Question
{
    public int QuestionId { get; set; }
    public int ProblemId { get; set; }
    public Guid QuestionUId { get; set; }
    // I think I will need to add this code here but I did not do it yet
    // public Question() {
    //    this.AdminTestQuestions = new HashSet<AdminTestQuestion>();
    // }
    // public virtual ICollection<AdmintestQuestion> AdminTestQuestions { get; set; }
}

public class Problem
{
    public Problem()
    {
        this.Questions = new HashSet<Question>();
    }
    public int ProblemId { get; set; }
    public int SubTopicId { get; set; }
    public virtual SubTopic SubTopic { get; set; }
    public virtual ICollection<Question> Questions { get; set; }
}

Simple, no you can't as you're working with a type that is defined at compile time. Your linq query runs at runtime and is bound to the types that were available at compile time.

Your only solution would be to create a new anonymous type but that's an entirely different solution.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM