我在问题与答案之间存在多对多关系。但是现在我想为有效的问答对增加成本。我试图考虑一种避免更改所有对原始属性的引用的方法。是否可以?
public class Question
{
public int ID { get; set:}
public string Text { get; set; }
//The original many-to-many
//public virtual ICollection<Answer> Answers { get; set; }
//but now I need a QuestionAnswerPair as an entity
//problem is that Adding or Removing does not affect the QuestionAnswerPairs collection
[NotMapped]
public ICollection<Answer> Answers
{
get
{
return QuestionAnswerPairs.Select(x => x.Answer).ToList();
}
}
public virtual ICollection<QuestionAnswerPair> QuestionAnswerPairs { get; set; }
}
public class Answer
{
public int ID {get; set;}
public string Text { get; set; }
//The original many-to-many
//public virtual ICollection<Question> Questions { get; set; }
}
//UnitCosts should only be added to valid Question-Answer pairs
//so I want to have a cost linked to the many-to-many relationship
public class QuestionAnswerPair
{
public int ID {get; set;}
public int AnswerID { get; set; }
public virtual Answer Answer { get; set; }
public int QuestionID { get; set; }
public virtual Question Question { get; set; }
public decimal? Amount { get; set; }
}
您很快就会发现,当您想在LINQ-to-entities查询中使用Navigation属性时,这是不可能的。
如果你愿意做
context.Questions.SelectMany(q => q.Answers)
EF将引发Answers
不支持的异常(仅支持初始化器,实体成员和实体导航属性)。
如果要解决此问题,请添加AsEnumerable
:
context.Questions.AsEnumerable().SelectMany(q => q.Answers)
您会发现,对于每个问题,都会执行查询以加载其QuestionAnswerPairs
集合和Answer
。(如果启用了延迟加载)。而且,如果您想避免这种情况,则必须获取带有Incude
语句的问题。
您确实无法做得更好,但是QuestionAnswerPairs
在LINQ查询中包括了。
这就是为什么使用透明联结表(即没有联结类)来实现多对多关联始终是一个重大决定的原因。用户迟早会希望将描述性数据添加到联结记录中。纯联结表在实际应用中非常罕见。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句