如何将左外连接查询的匿名类型结果转换为强类型

时间:2016-08-17 18:38:41

标签: c# linq entity-framework-6 type-conversion anonymous-types

以下是使用Answers查询左外联接问题

    var questions = db.Questions
    .Include(f => f.Category)
    .Where(p => p.Category_Id == forum.Category_Id)
    .GroupJoin(
        db.Answers.Where(p => p.Forum_Id == forum.Id),
        q => q.Id,
        a => a.Question_Id,
        (q, a) => new { Question = q, Answers = a.FirstOrDefault() }
   ).ToList();

我正在寻找将结果作为IEnumerable< Question>我可以访问Question对象的Navigation属性,例如

foreach (var question in questions)
{
    Console.WriteLine("Question: {0}", question.Text);
    if (question.Answers != null)
    {
        foreach (var answer in question.Answers)
        {
            Console.WriteLine("Answer: {0}", answer.Text);    
        }                    
    }        
}

此外,以下是我如何建立实体之间的关系:(请告知任何改进)

    modelBuilder.Entity<Forum>()
        .HasRequired<Category>(f => f.Category)
        .WithMany(f => f.Forums)
        .HasForeignKey(f => f.Category_Id);

    modelBuilder.Entity<Question>()
        .HasRequired<Category>(f => f.Category)
        .WithMany(q => q.Questions)
        .HasForeignKey(f => f.Category_Id)
        .WillCascadeOnDelete(false);

    modelBuilder.Entity<Answer>()
        .HasRequired<Forum>(q => q.Forum)
        .WithMany(k => k.Answers)
        .HasForeignKey(f => f.Forum_Id);

    modelBuilder.Entity<Answer>()
        .HasRequired<Question>(f => f.Question)
        .WithMany(f => f.Answers)
        .HasForeignKey(f => f.Question_Id)
        .WillCascadeOnDelete(false);



public class Forum
{
    public Guid Id { get; set; }

    public string Name { get; set; }
    public Guid Category_Id { get; set; }
    public virtual Category Category { get; set; }
    public virtual ICollection<Answer> Answers { get; set; }
    public Forum()
    {
        this.Answers = new HashSet<Answer>();
    }
}

public class Category
{
    public Guid Id { get; set; }
    public string Name { get; set; }
    public virtual ICollection<Forum> Forums { get; set; }
    public virtual ICollection<Question> Questions { get; set; }

    public Category()
    {
        this.Questions = new HashSet<Question>();
        this.Forums = new HashSet<Forum>();
    }
}

public class Question
{
    public Guid Id { get; set; }
    public string Text { get; set; }
    public virtual ICollection<Answer> Answers { get; set; }
    public Guid Category_Id { get; set; }
    public virtual Category Category { get; set; }
    public Question()
    {
        this.Answers = new HashSet<Answer>();
    }
}

public class Answer
{
    public Guid Id { get; set; }
    public string Text { get; set; }
    public Guid Question_Id { get; set; }
    public virtual Question Question { get; set; }
    public Guid Forum_Id { get; set; }
    public virtual Forum  Forum { get; set; }
    public Answer()
    {

    }
}

0 个答案:

没有答案