【问题标题】:telerik OpenAccess NULL reference in ASP.NET MVCASP.NET MVC 中的 Telerik OpenAccess NULL 参考
【发布时间】:2015-05-18 04:39:34
【问题描述】:

我在 ASP.NET MVC 5 中使用 Telerik 域模型。当我在单元测试项目中使用上下文时,一切正常。但是当我在 MVC 控制器上使用它时,我得到了这个异常:

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

谢谢

【问题讨论】:

  • 当我在 MVC 控制器上使用静态数据库上下文时,问题消失了。私有静态实体模型_DbContext;但我不能再处理上下文了。我认为这不是一个好习惯。谢谢

标签: c# asp.net-mvc telerik telerik-open-access openaccess


【解决方案1】:

经过多次尝试和错误,我找到了这个解决方案

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

我必须在初始化后查询数据库,否则我会得到空引用错误。如果有人有更好的解决方案或解释,我会很高兴知道。谢谢

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-10-05
    • 2015-04-07
    • 1970-01-01
    • 2010-10-01
    • 2011-06-12
    • 2012-07-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多