2

我在问题和答案之间有多对多的关系。但现在我想为有效的问答对增加成本。我试图想出一种方法来避免必须更改对原始属性的所有引用。可能吗?

   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; }
    }
4

1 回答 1

3

当您想在 LINQ-to-entities 查询中使用导航属性时,您很快就会发现这是不可能的。

如果你想做类似的事情

context.Questions.SelectMany(q => q.Answers)

EF 将抛出Answers不受支持的异常(仅支持初始化程序、实体成员和实体导航属性)。

如果您想通过添加来解决此问题AsEnumerable

context.Questions.AsEnumerable().SelectMany(q => q.Answers)

您会发现,对于每个问题,都会执行查询以加载它们的QuestionAnswerPairs集合和Answers. (如果启用了延迟加载)。如果你想防止这种情况发生,你必须用Incude陈述来获取问题。

QuestionAnswerPairs除了在 LINQ 查询中包含 之外,您真的不能做得更好。

这就是为什么用透明的联结表(即没有联结类)实现多对多关联总是一个重大决定。用户迟早会想要向联结记录添加描述性数据。纯接线表在实际应用中非常少见。

于 2013-11-06T08:25:52.133 回答