困擾了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.重新發布。
