[英]Save an inherited notmapped object to the base object using ef 5 code first
我有一個代碼第一個poco類叫做topic。 從這里我創建了一個名為topicWith的繼承類,它包含一些額外的聚合字段,如消息計數,以及在主題中創建消息的最后一個用戶。 在我的控制器中,我首先獲取一個主題,然后我想用基於它的讀取次數的+1更新基本主題。 如果我嘗試保存topicWith對象,我會收到一個錯誤:實體類型TopicWith不是當前上下文模型的一部分。 即使我明確地將對象強制轉換為“主題”,我也會得到這個
這是我正在做的簡短版本。
[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);
解決這個問題的最佳方法是什么?
可能解決方案
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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.