加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net-mvc-3 – 处理DbContext后的问题

发布时间:2020-12-16 04:26:16 所属栏目:asp.Net 来源:网络整理
导读:我最近更改了我的MVC3应用程序,试图正确处理DbContext对象[1].这在开发中运行得很好,但是一旦应用程序被推送到我的生产服务器,我就开始间歇性地获得一些有趣的例外,这些例外会一直存在,直到AppPool被回收.异常可以追溯到我的自定义AuthorizeAttribute中的代
我最近更改了我的MVC3应用程序,试图正确处理DbContext对象[1].这在开发中运行得很好,但是一旦应用程序被推送到我的生产服务器,我就开始间歇性地获得一些有趣的例外,这些例外会一直存在,直到AppPool被回收.异常可以追溯到我的自定义AuthorizeAttribute中的代码,如下所示:
System.InvalidOperationException: The 'Username' property on 'User' could not be set to a 'Int32' value. You must set this property to a non-null value of type 'String'.

System.InvalidOperationException: The 'Code' property on 'Right' could not be set to a 'String' value. You must set this property to a non-null value of type 'Int32'.

(数据库模式如下所示:用户:[Guid,String,…],权利:[Guid,Int32,…])

就好像某些“电线越过”,应用程序混合了数据库的结果:尝试以用户的形式实现正确的结果,反之亦然.

为了管理DbContext的处理,我把代码放在每个控制器级别存储它.当处理控制器时,我也处理DbContext.我知道它很hacky,但AuthorizeAttribute通过filterContext.Controller使用相同的上下文.

在这个庄园中处理DbContext的对象生命周期有什么问题吗?有没有任何合理的解释,为什么我得到上面的纵横交错的例外?

[1]虽然我知道没有必要处理DbContext对象,但我最近遇到了许多消息来源,说明这是最好的做法.

编辑(根据@ MikeSW的评论)

当AuthorizationContext在范围内时,OnAuthorization方法中正在设置表示DbContext的AuthorizeAttribute的属性.然后,此属性将在AuthorizeCore方法中使用.

解决方法

你真的需要处理上下文吗?

根据Jon Gallant的this post,他与Microsoft ADO.NET Entity Framework团队保持联系:

Do I always have to call Dispose() on my DbContext objects? Nope

Before I talked with the devs on the EF team my answer was always a resounding “of course!”. But it’s not true with DbContext. You don’t need to be religious about calling Dispose on your DbContext objects. Even though it does implement IDisposable,it only implements it so you can call Dispose as a safeguard in some special cases. By default DbContext automatically manages the connection for you.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读