0

I use telerik Domain Model for ASP.NET MVC 5. When I use context at Unit test project, all thing works perfectly. but when I use it at MVC Controllers I got this Exception:

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()

thanks

Mairaj Ahmad
  • 14,434
  • 2
  • 26
  • 40
Jake Terro
  • 11
  • 2
  • The problem is disappeared When I used static database context at MVC controller. private static EntitiesModel _DbContext; But I can't dispose the context anymore. and I think this is not a good practice. thanks – Jake Terro May 18 '15 at 05:04

1 Answers1

0

I found this solution after many trial and error

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;
    }
}

I must query the database after Initialize or I will get Null reference error. If anyone has better solution or explaination, I will be happy to know it. thanks

Jake Terro
  • 11
  • 2