将Microsoft.SqlServer.Types与Dapper一起使用时的RuntimeBinderInternalCompilerException

时间:2014-09-01 06:34:24

标签: .net sql-server dapper

使用其目标平台设置为以下之一的Sql Server Data Tools项目:

  • SQL Server 2008
  • SQL Server 2012
  • SQL Server 2014

并部署到(localdb)\ Projects或(localdb)\ ProjectsV12

调用返回Geometry,Geography或HierachyId类型的存储过程,例如:

CREATE PROCEDURE [dbo].[SelectSqlGeometry]
    @x Geometry
AS
    SELECT @x as y
RETURN 0

以下调用代码:

var result = Connection.Query("dbo.SelectSqlGeometry", new { x = geometry }, commandType: CommandType.StoredProcedure).First();
bool isSame = ((bool)geometry.STEquals(result.y));

在STEquals系列产生以下异常。

  

Microsoft.CSharp.RuntimeBinder.RuntimeBinderInternalCompilerException   用户代码未处理HResult = -2146233088消息= An   绑定动态操作时发生意外异常
  Source = Microsoft.CSharp StackTrace:          在Microsoft.CSharp.RuntimeBinder.RuntimeBinder.Bind(DynamicMetaObjectBinder   payload,IEnumerable 1 parameters, DynamicMetaObject[] args, DynamicMetaObject& deferredBinding) at Microsoft.CSharp.RuntimeBinder.BinderHelper.Bind(DynamicMetaObjectBinder action, RuntimeBinder binder, IEnumerable 1 args,IEnumerable 1 arginfos, DynamicMetaObject onBindingError) at Microsoft.CSharp.RuntimeBinder.CSharpConvertBinder.FallbackConvert(DynamicMetaObject target, DynamicMetaObject errorSuggestion) at System.Dynamic.DynamicMetaObject.BindConvert(ConvertBinder binder) at System.Dynamic.ConvertBinder.Bind(DynamicMetaObject target, DynamicMetaObject[] args) at System.Dynamic.DynamicMetaObjectBinder.Bind(Object[] args, ReadOnlyCollection 1个参数,LabelTarget returnLabel)          在System.Runtime.CompilerServices.CallSiteBinder.BindCore [T](CallSite`1   site,Object [] args)          在System.Dynamic.UpdateDelegates.UpdateAndExecute1 [T0,TRet](CallSite)   网站,T0 arg0)          在DATailor.Examples.Dapper.SqlClient.Test.AllTypesDAOTest.TestAllTypesDynamic()

1 个答案:

答案 0 :(得分:7)

虽然根本原因不是Dapper,但是有一个潜在的异常被吞下。

使用ADO.Net代码,如:

var geometry = Util.CreateSqlGeometry();
SqlDataReader reader=null;
SqlCommand cmd=null;
try
{
    cmd = new SqlCommand("dbo.SelectSqlGeometry", (SqlConnection)Connection);
    cmd.CommandType = CommandType.StoredProcedure;
    cmd.Parameters.Add(new SqlParameter("@x", geometry) { UdtTypeName = "Geometry" });
    cmd.ExecuteNonQuery();
    reader = cmd.ExecuteReader();
    while (reader.Read())
    {
        var y = (SqlGeometry)reader.GetValue(0);
        var same = geometry.STEquals(y);
    }
    reader.Dispose();
    reader = null;
}
finally
{
    if (reader != null)
    {
        if (!reader.IsClosed) try { cmd.Cancel(); }
            catch {}
        reader.Dispose();
    }
    if (cmd != null) cmd.Dispose();
    Connection.Close();
}

reader.GetValue

引发了以下异常
  

System.InvalidCastException未处理HResult = -2147467262
  消息= [A] Microsoft.SqlServer.Types.SqlGeometry无法强制转换为   [B] Microsoft.SqlServer.Types.SqlGeometry。 A型起源于   'Microsoft.SqlServer.Types,Version = 10.0.0.0,Culture = neutral,   PublicKeyToken = 89845dcd8080cc91'在上下文'默认'位置   'C:\ WINDOWS \装配\ GAC_MSIL \ Microsoft.SqlServer.Types \ 10.0.0.0__89845dcd8080cc91 \ Microsoft.SqlServer.Types.dll'。   类型B源自'Microsoft.SqlServer.Types,Version = 11.0.0.0,   在上下文中,Culture = neutral,PublicKeyToken = 89845dcd8080cc91'   位置处的“默认”   'C:\ WINDOWS \装配\ GAC_MSIL \ Microsoft.SqlServer.Types \ 11.0.0.0__89845dcd8080cc91 \ Microsoft.SqlServer.Types.dll'。   Source = DynamicGeometryIssue StackTrace:          at C:\ Users \ rich \ Documents \ Visual Studio中的DynamicGeometryIssue.TestDao.TestGeometry()   2013 \项目\ DynamicGeometryIssue \ DynamicGeometryIssue \ TestDao.cs:行   27          在C:\ Users \ rich \ Documents \ Visual Studio中的DynamicGeometryIssue.Program.Main(String [] args)   2013 \项目\ DynamicGeometryIssue \ DynamicGeometryIssue \的Program.cs:行   15          在System.AppDomain._nExecuteAssembly(RuntimeAssembly程序集,String [] args)          在System.AppDomain.ExecuteAssembly(String assemblyFile,Evidence assemblySecurity,String [] args)          在Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()          在System.Threading.ThreadHelper.ThreadStart_Context(对象状态)          在System.Threading.ExecutionContext.RunInternal(ExecutionContext   executionContext,ContextCallback回调,对象状态,布尔值   preserveSyncCtx)          at System.Threading.ExecutionContext.Run(ExecutionContext executionContext,ContextCallback callback,Object state,Boolean   preserveSyncCtx)          在System.Threading.ExecutionContext.Run(ExecutionContext executionContext,ContextCallback回调,对象状态)          在System.Threading.ThreadHelper.ThreadStart()InnerException:

基础异常的原因是SQL Server 2012中已知的重大更改。请参阅以下MSDN文档的 SQL CLR数据类型部分

http://msdn.microsoft.com/en-us/library/ms143179(v=sql.110).aspx

对我有用的解决方案是在app.config或web.config中创建以下bindingRedirect。

<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
  <dependentAssembly>
    <assemblyIdentity name="Microsoft.SqlServer.Types"
                      publicKeyToken="89845dcd8080cc91"
                      culture="neutral" />
    <bindingRedirect oldVersion="10.0.0.0"
                     newVersion="11.0.0.0"/>
  </dependentAssembly>
</assemblyBinding>
</runtime>

或者,使用.NET 4.5,您可以更改连接字符串以包含“Type System Version”属性的值“SQL Server 2012”,以强制SqlClient加载程序集的版本11.0。

另一种解决方法是代码:

var geo = SqlGeography.Deserialize(rdr.GetSqlBytes(0));

但是,我不相信这是Dapper的选择。