The entity type XXXInfo is not part of the model for the current context.

困扰了2天的问题终于解决,心情真好!写程序就是这样,找不到解决方法之前的小问题就是大问题!

最近在.net mvc3开源项目NopCommerce的基础上开发的一个管理系统,前天突然遇到了一个问题:The entity type XXXInfo is not part of the model for the current context. 

问题描述:

1.用VS生成后,直接测试是没有问题的;

2.重启3W服务或回收程序池后,错误会出现;

3.发布这后和第2点一样;

跟踪调试后如下图:

插序:发现问题就在baidu和google上去狂搜,但最终还是没有找到问题所在。值得注意的是:搜索到的类似问题还真不少;

解决此问题之后觉得这是养成的最不好的习惯——发现问题就找两位"搜哥"。其实回头来细分析一下,找到原因也应该是不难的。

然后在此这前,我已经做了以下3步,并且认真的核对了一下表名及字段对应model属性:

以下说明以新建的Test2表为例

1.XX.Core项目中:

新建model

[DataContract]
    public partial class Test2:BaseEntity
    {
        [DataMember]
        public string Name { get; set; }
    }

2.XX.Data项目中:

新建map

 public partial class Test2Map : EntityTypeConfiguration<Test2>
    {
        public Test2Map()
        {
            this.ToTable("Test2");
            this.HasKey(l => l.Id);
        }
    }

3.XX.Services项目中:

新建接口

    public class Test2Service : ITest2Service
    {
        private readonly IRepository<Test2> _test2Repository;
        public Test2Service(IRepository<Test2> test2Repository)
        {
            _test2Repository = test2Repository;
        }
        public Test2 GetTest2First()
        {
            return _test2Repository.Table.First();
        }
    }

实现:

  public class Test2Service : ITest2Service
    {
        private readonly IRepository<Test2> _test2Repository;
        public Test2Service(IRepository<Test2> test2Repository)
        {
            _test2Repository = test2Repository;
        }
        /// <summary>
        /// 获取第一行数据
        /// </summary>
        /// <returns></returns>
        public Test2 GetTest2First()
        {
            return _test2Repository.Table.First();
        }
    }

4.XX.Web.Framework项目中:

在DependencyRegistrar.cs中注册接口

 builder.RegisterType<Test2Service>().As<ITest2Service>().InstancePerDependency();

以下方法均无效,且勿模仿:

1.删除core,data,services重新创建三者

2.删除三者的相互引用,重新添加三者的依赖关系

3.跟踪调试也无济于事

4.写日志,跟踪

5.郁闷——更是没用

6.好好研究研究NopCommerce的代码——当然有好处,可能也难解决此问题,但是可能时间不允许

7.重装IIS(因为现象是重起IIS后问题才出现的)——这个方法我没试,哈哈,应该肯定是浪费时间而无功的事

8.用google搜索到的答案,也没用:

测试了一通之后,问题解决的方法也异常的简单:

在NopCommerce中有一个插件机制,应该来说这是这个开源项目的特色功能之一(Plugins目录上的所有项目),当然在插件项目中也需要引用Core和services项目的,

我再去看web项目发现当中有引用一个插件项目,这就是问题所在:

Plugins依赖:Core,data,services

web项目依赖:Core,data,Plugins,sevices

Plugins插件:会生成到另外一个单独的目录

所以,生成之后的web项目的Core,data,services与Plugins插件生的目录中的Core,data,services不一致才造成了问题的发生。

解决方法:

1.删除所有无须引用的依赖项目,更不能存在递归依赖的情况。

2.重新编译所有项目。

3.重新发布。

原文地址:https://www.cnblogs.com/zwjaaron/p/2541430.html