本文介绍了间歇"指定的转换是无效的"与StructureMap注入数据上下文的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我间歇性地收到一个 System.InvalidCastException:时执行无效在我的仓库层错误的抽象 SELECT 查询映射到LINQ。

该错误不能被不匹配的数据库模式,因为它的工作原理间歇性造成的,这是在我的本地开发机器。

这可能是因为StructureMap是缓存页面请求的数据上下文?如果是这样,我怎么告诉StructureMap V2.6.1到一个新的数据上下文参数到我的仓库为每个请求?

注入

更新:我发现this问题其关联我的预感,在被重新使用的东西。看起来我需要调用Dispose我注入数据上下文。不知道我会怎么做这的所有的我的资料库没有copypasting很多code。

修改:这些错误如雨后春笋般冒出遍布每当我刷新我的本地机器的速度太快的地方。看起来并不像它的发生在我的远程部署中,但我不能肯定。

我改变了我所有的资料库StructureMap生命周期 HttpContextScoped()和错误仍然存​​在。

code:

 公众的ActionResult指数()
{
    //错误发生在这里,它询问我的网页库
    VAR页= _branchService.GetPage(欢迎);
    如果(页面!= NULL)
    计算机[欢迎] = page.Body;
    ...
}
 

存储库:

GetPage中归结到我的网页库中的过滤查询映射。

 公开的IQueryable<第> GETPAGES()
{
    VAR页=从p在_db.Pages
        让类别= GetPageCategories(p.PageId)
        让我们修改= GetRevisions(p.PageId)
        选择新页面
        {
            ID = p.PageId,
            用户名= p.UserId,
            弹头= p.Slug,
            标题= p.Title,
            说明= p.Description,
            车身= p.Text,
            日期= p.Date,
            |评论= p.IsPublished,
            分类=新LazyList<类别>(分类),
            修订=新LazyList< PageRevision>(修正)
        };

        返回页面;
}
 

在这里_db是注入的数据上下文作为参数,存储在我重新使用SELECT查询一个私有变量。

调用code:

 公共页面GetPage中(串塞)
{
    返回_pageRepository.GetPages()
                          .WithSlug(塞).FirstOrDefault();
}
 

WithSlug 只是一个管道过滤器,增加了一个where子句来查询。

错误:

 指定的转换是无效的。
异常详细信息:System.InvalidCastException:指定强制转换为无效。
 

堆栈跟踪:

  [InvalidCastException的:指定的转换是无效的。]
   System.Data.Linq.SqlClient.SqlProvider.Execute(前pression查询,QueryInfo queryInfo,IObjectReaderFactory厂,对象[] parentArgs,对象[] userArgs,ICompiledSubQuery []子查询,对象的lastResult)4539
   System.Data.Linq.SqlClient.SqlProvider.ExecuteAll(前pression查询,QueryInfo [] queryInfos,IObjectReaderFactory厂,对象[] userArguments,ICompiledSubQuery []子查询)207
   System.Data.Linq.SqlClient.SqlProvider.System.Data.Linq.Provider.IProvider.Execute(前pression查询)+500
   System.Data.Linq.DataQuery`1.System.Linq.IQueryProvider.Execute(前pression EX pression)+50
   System.Linq.Queryable.FirstOrDefault(IQueryable`1源)383
   Manager.Controllers.SiteController.Index()在C:\项目\管理\管理\控制器\ SiteController.cs:68
   lambda_method(封闭,ControllerBase,对象[])+79
   System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext,IDictionary`2参数)+258
   System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext,ActionDescriptor actionDescriptor,IDictionary`2参数)+39
   System.Web.Mvc<>。c__DisplayClassd< InvokeActionMethodWithFilters> b__a()+125
   System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodFilter(IActionFilter过滤器,ActionExecutingContext preContext,Func`1续)+ 640
   System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodWithFilters(ControllerContext controllerContext,IList`1过滤器,ActionDescriptor actionDescriptor,IDictionary`2参数)312
   System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext controllerContext,字符串actionName)709
   System.Web.Mvc.Controller.ExecuteCore()+162
   System.Web.Mvc<> c__DisplayClass8< BeginProcessRequest> b__4()+58
   System.Web.Mvc.Async<> c__DisplayClass1< MakeVoidDelegate> b__0()+20
   System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()453
   System.Web.HttpApplication.ExecuteStep(IExecutionStep步骤,布尔和放大器; completedSynchronously)+371
 

解决方案

瞎搞与处置库并没有帮助,但设置MultipleActiveResultsets为true,我的SQL连接字符串中解决了这个问题。

I am intermittently getting an System.InvalidCastException: Specified cast is not valid. error in my repository layer when performing an abstracted SELECT query mapped with LINQ.

The error can't be caused by a mismatched database schema since it works intermittently and it's on my local dev machine.

Could it be because StructureMap is caching the data context between page requests? If so, how do I tell StructureMap v2.6.1 to inject a new data context argument into my repository for each request?

Update: I found this question which correlates my hunch that something was being re-used. Looks like I need to call Dispose on my injected data context. Not sure how I'm going to do this to all my repositories without copypasting a lot of code.

Edit: These errors are popping up all over the place whenever I refresh my local machine too quickly. Doesn't look like it's happening on my remote deployment box, but I can't be sure.

I changed all my repositories' StructureMap life cycles to HttpContextScoped() and the error persists.

Code:

public ActionResult Index()
{
    // error happens here, which queries my page repository
    var page = _branchService.GetPage("welcome");
    if (page != null)
    ViewData["Welcome"] = page.Body;
    ...
}

Repository:

GetPage boils down to a filtered query mapping in my page repository.

public IQueryable<Page> GetPages()
{
    var pages = from p in _db.Pages
        let categories = GetPageCategories(p.PageId)
        let revisions = GetRevisions(p.PageId)
        select new Page
        {
            ID = p.PageId,
            UserID = p.UserId,
            Slug = p.Slug,
            Title = p.Title,
            Description = p.Description,
            Body = p.Text,
            Date = p.Date,
            IsPublished = p.IsPublished,
            Categories = new LazyList<Category>(categories),
            Revisions = new LazyList<PageRevision>(revisions)
        };

        return pages;
}

where _db is an injected data context as an argument, stored in a private variable which I reuse for SELECT queries.

Calling code:

public Page GetPage(string slug)
{
    return _pageRepository.GetPages()
                          .WithSlug(slug).FirstOrDefault();
}

WithSlug is just a pipeline filter that adds a where clause to the query.

Error:

Specified cast is not valid.
Exception Details: System.InvalidCastException: Specified cast is not valid.

Stack Trace:

[InvalidCastException: Specified cast is not valid.]
   System.Data.Linq.SqlClient.SqlProvider.Execute(Expression query, QueryInfo queryInfo, IObjectReaderFactory factory, Object[] parentArgs, Object[] userArgs, ICompiledSubQuery[] subQueries, Object lastResult) +4539
   System.Data.Linq.SqlClient.SqlProvider.ExecuteAll(Expression query, QueryInfo[] queryInfos, IObjectReaderFactory factory, Object[] userArguments, ICompiledSubQuery[] subQueries) +207
   System.Data.Linq.SqlClient.SqlProvider.System.Data.Linq.Provider.IProvider.Execute(Expression query) +500
   System.Data.Linq.DataQuery`1.System.Linq.IQueryProvider.Execute(Expression expression) +50
   System.Linq.Queryable.FirstOrDefault(IQueryable`1 source) +383
   Manager.Controllers.SiteController.Index() in C:\Projects\Manager\Manager\Controllers\SiteController.cs:68
   lambda_method(Closure , ControllerBase , Object[] ) +79
   System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters) +258
   System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +39
   System.Web.Mvc.<>c__DisplayClassd.<InvokeActionMethodWithFilters>b__a() +125
   System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodFilter(IActionFilter filter, ActionExecutingContext preContext, Func`1 continuation) +640
   System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodWithFilters(ControllerContext controllerContext, IList`1 filters, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +312
   System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext controllerContext, String actionName) +709
   System.Web.Mvc.Controller.ExecuteCore() +162
   System.Web.Mvc.<>c__DisplayClass8.<BeginProcessRequest>b__4() +58
   System.Web.Mvc.Async.<>c__DisplayClass1.<MakeVoidDelegate>b__0() +20
   System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +453
   System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +371
解决方案

Messing around with disposing repositories didn't help, but setting MultipleActiveResultsets to true in my SQL connection string solved the problem.

这篇关于间歇&QUOT;指定的转换是无效的&QUOT;与StructureMap注入数据上下文的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-28 03:43