简体   繁体   English

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

[英]Save an inherited notmapped object to the base object using ef 5 code first

I have a code first poco class called topic. 我有一个代码第一个poco类叫做topic。 From this I've created an inherited class called topicWith that contains some extra aggregated fields like the message count, and the last user that created a message within a topic. 从这里我创建了一个名为topicWith的继承类,它包含一些额外的聚合字段,如消息计数,以及在主题中创建消息的最后一个用户。 In my controller I fetch a topicWith first, then I would like to update the base topic with +1 on the number of times it's been read. 在我的控制器中,我首先获取一个主题,然后我想用基于它的读取次数的+1更新基本主题。 If I try to save the topicWith object I get an error: The entity type TopicWith is not part of the model for the current context. 如果我尝试保存topicWith对象,我会收到一个错误:实体类型TopicWith不是当前上下文模型的一部分。 I get this even though I've explicitly cast the object to "topic" 即使我明确地将对象强制转换为“主题”,我也会得到这个

This is the short version of what I'm doing. 这是我正在做的简短版本。

[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);

What is the best way to solve this problem? 解决这个问题的最佳方法是什么?

Possible solution 可能解决方案

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