从物化的"System.Guid"类型到"System.Int32"类型的指定强制转换无效

Ric*_*iak 14 c# wcf sql-server-2005 sql-server-2008 entity-framework-4

The specified cast from a materialized 'System.Guid' type to the 'System.Int32' type is not valid.

我们有几个WCF服务,其并发模式为Multiple和InstanceContextModeSingle.我们的架构侧重于使用基于构造函数的依赖注入的松散耦合模型.这反过来是使用Unity 2.0实现的(每个服务的web.config都具有在统一容器部分中定义的接口和类型之间的映射).我们的依赖项之一是使用Entity Framework 4与MSSql Server通信的DAL程序集(数据访问层).与数据库通信的类也包含在单位映射中.

当我们运行集成测试时,一切都很棒.但是当我们转移到我们的性能环境来运行负载测试(2,3,4个并发用户)时,我们开始看到以下错误:

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

使用以下堆栈:

at System.Data.Common.Internal.Materialization.Shaper.ErrorHandlingValueReader`1.GetValue(DbDataReader reader, Int32 ordinal)
at System.Data.Common.Internal.Materialization.Shaper.GetPropertyValueWithErrorHandling[TProperty](Int32 ordinal, String propertyName, String typeName)
at lambda_method(Closure , Shaper )
at System.Data.Common.Internal.Materialization.Shaper.HandleEntityAppendOnly[TEntity](Func`2 constructEntityDelegate, EntityKey entityKey, EntitySet entitySet)
at lambda_method(Closure , Shaper )
at System.Data.Common.Internal.Materialization.Coordinator`1.ReadNextElement(Shaper shaper)
at System.Data.Common.Internal.Materialization.Shaper`1.SimpleEnumerator.MoveNext()
at System.Linq.Enumerable.First[TSource](IEnumerable`1 source)
at System.Linq.Queryable.First[TSource](IQueryable`1 source)
at MISoa.DataAccessLayer.Authentication.AuthenticationDB.RetrieveSession(Guid authToken)
at MISoa.DataAccessLayer.Authentication.AuthenticationAccess.RetrieveSession(String sessionToken)
Run Code Online (Sandbox Code Playgroud)

这是罪魁祸首方法:

public Session RetrieveSession(Guid authToken)
    {
        CheckDBContext();
        var sessions = (from r in _dbContext.Sessions
                where r.auth_token == authToken
                select r);
        return sessions.Count() > 0 ? sessions.First() : null;
    }
Run Code Online (Sandbox Code Playgroud)

CheckDBContext 方法只是检查db上下文是否为null,如果是,则抛出自定义异常.

emdx会话实体对象具有以下公共属性:

Guid auth_token
DateTime time_stamp
String user_id
String app_id
Run Code Online (Sandbox Code Playgroud)

所以,看起来有时上面的linq从数据库返回一些其他对象,其中第一列是a int而不是guid?如果是这样 - 为什么?我是否有多个线程覆盖彼此的db上下文的问题?BTW - 我们将实例化db上下文的代码抽象为一个单独的类(BaseDB),该类也由unity处理.所以,因为服务是一个单身人士,所以每个人都有一个BaseDB实例,对吗?这是问题吗?

哦,还有一件事.我们被告知我们将在edmx文件中使用MSSql 2005 ProviderManifestToken="2005".但我刚检查过,我们的性能数据库服务器是2008版本.这是一个问题吗?

谢谢您的帮助.

Rob*_*los 2

我是否遇到多个线程覆盖彼此的数据库上下文的问题?

是的。请参阅此处:http ://msdn.microsoft.com/en-us/library/system.data.objects.objectcontext.aspx

引用上面链接中黄色大框的内容:

该类ObjectContext不是线程安全的。ObjectContext在多线程场景下,无法保证an中数据对象的完整性。

您可能需要考虑将其放在[ThreadStaticAttribute]您的_dbContext领域中。