我想只返回aapprove值为1的答案。 这是我的Answer.cs:
public partial class Answer
{
public int aid { get; set; }
public string abody { get; set; }
public Nullable<System.DateTime> adate { get; set; }
public Nullable<int> alikes { get; set; }
public int uid { get; set; }
public int qid { get; set; }
public int Question_qid { get; set; }
public Nullable<int> aapprove { get; set; }
public virtual Question Question { get; set; }
}
和我的Question.cs:
public partial class Question
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public Question()
{
this.Answers = new HashSet<Answer>();
}
public int qid { get; set; }
public string qtitle { get; set; }
public string qbody { get; set; }
public string qtags { get; set; }
public Nullable<int> qlikes { get; set; }
public Nullable<int> qcomments { get; set; }
public int uid { get; set; }
public Nullable<System.DateTime> qdate { get; set; }
public int User_uid { get; set; }
public Nullable<int> qapprove { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<Answer> Answers { get; set; }
}
在我的控制器中,我正在做,
List<Question> questions = entities.Questions
.Include("Answers")
.Where(q => q.qapprove == 1)
.ToList();
这是返回数组,如:
{
"qid": 1,
"qtitle": "What is the fees of xyz college",
"qbody": "I wanted to know the fees of xyz MBBS college. Please help if any one knows.",
"qtags": "FEES",
"qlikes": 1,
"qcomments": 14,
"uid": 1,
"qdate": "2017-03-12T04:35:00",
"User_uid": 1,
"qapprove": 1,
"Answers": [
{
"aid": 1,
"abody": "The fees of this college is not very high. Average people can manage easily.",
"adate": "2017-01-02T04:35:00",
"alikes": 15,
"uid": 1,
"qid": 1,
"Question_qid": 1,
"aapprove": 0
}
]
}
我想只返回那些批准值为1的答案。(包括(&#34;答案&#34;)正在返回我不想要的所有答案。)我该怎么办?< / p>
答案 0 :(得分:1)
您可以使用select来加载数据,实体框架将负责附加
var data = entities.Questions
.Include("Answers")
.Where(q => q.qapprove == 1)
.Select(x => new { Questions = x, Answers =
x.Answers.Where(a => /*Your condition*/)})
.ToList();
var questions = data.Select(x => x.Questions).ToList();
答案 1 :(得分:0)
你可以从另一方面接近它
var questions = entities.Answers
.Where(answer => answer.aapprove == 1)
.GroupBy(answer => answer.Question_qid)
.Select(group => new {
Question = group.First().Question,
Answers = group;
});