2013-03-10 10 views
0

我有一個代碼,第一個叫做topic的poco類。從這裏我創建了一個名爲topicWith的繼承類,它包含一些額外的聚合字段,如消息計數和在主題內創建消息的最後一個用戶。在我的控制器中,我首先獲取topicWith,然後我想用基於+1的次數更新基本主題。如果我嘗試保存topicWith對象,則會出現錯誤:實體類型TopicWith不是當前上下文的模型的一部分。即使我明確將對象投射到「主題」,我也會得到這個結果首先使用ef 5代碼將繼承的未映射對象保存到基礎對象

這是我正在做的簡短版本。

[NotMapped] 
public class TopicWith : Topic 
{ 
    public virtual int NumberOfMessages { get; set; } 
} 

var topics = from topic in context.Topics 
       select 
        new TopicWith 
         { 
          ForumID = topic.ForumID, 
          TopicID = topic.TopicID, 
          Subject = topic.Subject, 
          Hide = topic.Hide, 
          Locked = topic.Locked, 
          Icon = topic.Icon, 
          NoOfViews = topic.NoOfViews, 
          Priority = topic.Priority, 
          Forum = topic.Forum, 
          Messages = topic.Messages, 
          NumberOfMessages = topic.Messages.Count() 
         }; 
var topicWith = topics.FirstOrDefault(); 
topicWith.NoOfViews++; 
context.Topics.Add((Topic) topicWith); 

解決此問題的最佳方法是什麼?

回答

2

可能的解決方法

var topics = from topic in context.Topics 
      select 
       new { 
         Topic = topic, 
         NumberOfMessages = topic.Messages.Count() 
        }; 
var topicWith = topics.FirstOrDefault(); 
topicWith.Topic.NoOfViews++; 
context.Topics.Add(topicWith.Topic);