0

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

谢谢

4

1 回答 1

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

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

于 2015-05-18T08:01:02.017 回答