我是否可以在不更改对现有导航属性的所有引用的情况下提升与实体的多对多关系?

时间:2013-11-05 14:22:21

标签: entity-framework

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

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

1 个答案:

答案 0 :(得分:3)

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

如果你做的话

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

EF将抛出不支持Answers的异常(仅支持初始值设定项,实体成员和实体导航属性)。

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

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

您会发现每个问题都会执行查询以加载他们的QuestionAnswerPairs集合和Answer。 (如果启用了延迟加载)。如果你想阻止那个,你必须用Incude语句来提问。

你真的不能做更好的事情,但在你的LINQ查询中包含QuestionAnswerPairs

这就是为什么使用透明连接表(即没有连接类)实现多对多关联始终是一个重大决定。用户迟早要将描述性数据添加到联结记录中。纯接点表在实际应用中非常罕见。

相关问题