简体   繁体   中英

telerik OpenAccess NULL reference in ASP.NET MVC

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM