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.