Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/309.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 首先使用ef 5代码将继承的notmapped对象保存到基本对象_C#_Entity Framework - Fatal编程技术网

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

C# 首先使用ef 5代码将继承的notmapped对象保存到基本对象,c#,entity-framework,C#,Entity Framework,我有一个名为topic的代码优先poco类。由此,我创建了一个名为topicWith的继承类,该类包含一些额外的聚合字段,如message count,以及在主题中创建消息的最后一个用户。在我的控制器中,我首先获取一个topicWith,然后我想用+1更新基本主题的读取次数。如果我试图保存topicWith对象,我会得到一个错误:实体类型topicWith不是当前上下文的模型的一部分。即使我已经将对象显式地强制转换为“主题”,我也会得到这个结果 这是我正在做的事情的简短版本 [NotMapped

我有一个名为topic的代码优先poco类。由此,我创建了一个名为topicWith的继承类,该类包含一些额外的聚合字段,如message count,以及在主题中创建消息的最后一个用户。在我的控制器中,我首先获取一个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);