繁体   English   中英

首先使用ef 5代码将继承的notmapped对象保存到基础对象

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM