我有以下代码
public class Question
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public long Id { get; set; }
[Required]
public string QuestionText { get; set; }
public virtual ICollection<QuestionOption> QuestionOptions { get; set; }
}
public class QuestionOption
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public long Id { get; set; }
[Required]
public string OptionText { get; set; }
[ForeignKey("QuestionId")]
public Question Question { get; set; }
public long QuestionId { get; set; }
public virtual ICollection<QuestionOptionAnswer> QuestionOptionAnswers { get; set; }
}
public class QuestionOptionAnswer
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public long Id { get; set; }
[ForeignKey("QuestionOptionId")]
public QuestionOption QuestionOption { get; set; }
public long QuestionOptionId { get; set; }
}
和以下查询来检索问题:
var dbResult = await (from question in context.Question.Include(x => x.QuestionOptions).ThenInclude(x => x.QuestionOptionAnswers)
where question.Id == id
select question).FirstOrDefaultAsync();
一切正常,查询返回我真正需要的东西,除了我可以在QuestionOption中看到已经拥有的父Entity(Question)的事实。我遇到的情况是,一个问题有10个问题选项,每个选项都有问题父级实体返回。这是不希望的,因为我得到的东西已经多次出现。如何防止这种情况发生?
答案 0 :(得分:-1)
您不会多次获取父对象,每个父对象从数据库中作为一行返回,并且为每个QuestionOption
创建一个对象。
尽管它在多个地方都被引用,包括您的 def binary_search(seq,item):
"""It uses non recursive method to search the item in the given seq.
It returns the position of item if found, None otherwise"""
left_index=0
right_index=len(seq)-1
while left_index <= right_index: #stop searching when left_index > right_indext
mid_index=(right_index + left_index)//2 #find the mid point
if seq[mid_index]==item:
return mid_index
elif seq[mid_index]>item:
right_index = mid_index -1 #if mid point ele > search ele, move right pointer
else:
left_index = mid_index + 1 #if mid point ele < search ele, move left pointer
return None
a=[1,2,3,4,5,6,7,8,9]
print(binary_search(a,6))
,但对性能的影响很小。