我的问题和答案之间有很多种关系。但现在,我想在有效的问答对中添加一个成本。我试图想出一种避免更改所有对原始属性的引用的方法。有可能吗?
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; }
}发布于 2013-11-06 08:25:52
您很快就会发现,当您想在查询中使用导航属性时,这是不可能的。
如果你能做点什么
context.Questions.SelectMany(q => q.Answers)EF将引发不支持Answers的异常(只支持初始化器、实体成员和实体导航属性)。
如果您想通过添加AsEnumerable来解决这个问题
context.Questions.AsEnumerable().SelectMany(q => q.Answers)您将发现,对于每个问题,执行查询都是为了加载它们的QuestionAnswerPairs集合和Answer。(如果启用了延迟加载)。如果您想防止这种情况发生,就必须使用Incude语句来获取问题。
除了在LINQ查询中包含QuestionAnswerPairs之外,您真的不能做更好的事情了。
这就是为什么使用透明的连接表(即没有连接类)来实现多到多的关联总是一个重大的决定。用户迟早会想要向连接记录中添加描述性数据。纯连接表在实际应用中非常少见。
https://stackoverflow.com/questions/19791189
复制相似问题