这就是我的数据库代码:
public class Question {
public int Id {get; set;}
public ICollection<Answer> Answers {get; set;}
public Question() {
Answers = new List<Answer>();
}
}
public class Answer {
public ind Id {get; set;}
public string Message {get; set;}
public int QuestionId { get; set; }
[ForeignKey("QuestionId")]
public Question Question { get; set; }
public int? PictureId { get; set; }
[ForeignKey("PictureId")]
public Picture Picture { get; set; }
public int KeywordId { get; set; }
[ForeignKey("KeywordId")]
public Keyword Keyword { get; set; }
public int? VideoId { get; set; }
[ForeignKey("VideoId")]
public Video Videos { get; set; }
}
public class Picture {
public int Id {get; set;}
public string Url {get; set;}
}
public class Keyword {
public int Id {get; set;}
public string Text {get; set;}
}
public class Video {
public int Id {get; set;}
public string Url {get; set;}
}
我想要存档的是加载带有图片和关键字的答案的所有问题(我不想加载Video
。此代码:
public static List<Question> GetQuestions() {
using (var context = new DatabaseContext()) {
return context.Questions
.Include(x => x.Answers.Select(y => y.Keyword))
.ToList();
}
}
用关键字向我提出所有答案的所有问题。我真的不知道如何附上图片。我认为有更好的方法来做到这一点,而不是逐个选择所有对象(我仍然不确定是否可能)。你能帮帮我吗?
答案 0 :(得分:0)
您可以使用Include
的重载,允许您使用表示您可能需要的任何属性的字符串。
context.Questions.Include("Answers.Picture")
.Include("Answers.Keyword")
.ToList();
答案 1 :(得分:0)
只需尝试:
return context.Questions
.Include(x => x.Answers.Select(y => y.Keyword))
.Include(x => x.Answers.Select(y => y.Picture))
.ToList();
或使用最后选择的投影(无论如何都会忽略所有包含):
return context.Questions
.Select(x => new Answers(){x.Keyword,x.Picture }
.ToList();