2015-05-18 81 views
0

我對ASP.NET MVC 5使用telerik域模型。當我在單元測試項目中使用上下文時,所有的東西都完美地工作。但是當我在MVC控制器使用它,我得到這個異常:Telerik OpenAccess ASP.NET MVC中的NULL引用

System.NullReferenceException: Object reference not set to an instance of an object. 
at Telerik.OpenAccess.RT.Adonet2Generic.Impl.DBDriver.connect(ConnectionString connectionString, PropertySet driverProps, ConnectionPoolType poolType, LogEventStore pes) 
at OpenAccessRuntime.Relational.sql.SqlDriver.InitializeFor(ConnectionString connectionString, Boolean noConnect, PropertySet props, DBDriver& driver, Connection& conn, ConnectionPoolType poolType) 
at OpenAccessRuntime.Relational.RelationalStorageManagerFactory..ctor(StorageManagerFactoryBuilder b) 
at OpenAccessRuntime.storagemanager.StorageManagerFactoryBuilder.createSmfForURL() 

感謝

+0

問題消失當我在MVC控制器上使用靜態數據庫上下文。 private static EntitiesModel _DbContext; 但我無法處理上下文了。我認爲這不是一個好的做法。謝謝 –

回答

0

我發現了許多試驗和錯誤之後該方案

public class MyController : Controller 
{ 
    private EntitiesModel _dbContext; 
    protected override void Initialize(System.Web.Routing.RequestContext requestContext) 
    { 
     base.Initialize(requestContext); 
     this._dbContext = ContextFactory.GetContextPerRequest(); 

     //the problem is disappeared after add this line 
     var obj = this._dbContext.AnyTable.FirstOrDefault(); 
    } 

    public ActionResult Index() 
    { 
     var q = _dbContext.AnyTable.ToList(); 
     return View(q); //Now It works like charm 
    } 
} 

public class ContextFactory 
{ 
    private static readonly string ContextKey = typeof(EntitiesModel).FullName; 
    public static EntitiesModel GetContextPerRequest() 
    { 
     var httpContext = HttpContext.Current; 
     if (httpContext == null) 
     { 
      return new EntitiesModel(); 
     } 
     var context = httpContext.Items[ContextKey] as EntitiesModel; 
     if (context != null) return context; 
     context = new EntitiesModel(); 
     httpContext.Items[ContextKey] = context; 
     return context; 
    } 
} 

我必須初始化或者我以後查詢數據庫會得到Null引用錯誤。如果有人有更好的解決方案或解釋,我會很樂意知道它。謝謝