Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dapper ambiguous extension methods

Tags:

c#

dapper

I am testing Dapper as a ORM solution and ran into a problem with some extension methods like Execute or QueryMultiple:

using (SQLiteConnection con = new SQLiteConnection(GetConnectionString()))
{
    con.Open();
    string sql = @"
        select * from Customer where Id = @id;
        select * from Address where CustomerId = @id;";

    // QueryMultiple extension ambiguous?
    using (var multi = con.QueryMultiple(sql, new { id = 1 }))
    {
        Customer customer = multi.Read<Customer>().Single();
        Address address = multi.Read<Address>().Single();
    }

    con.Close();
}

I get the error

The call is ambiguous between the following methods or properties: 'Dapper.SqlMapper.QueryMultiple(System.Data.IDbConnection, string, object, System.Data.IDbTransaction, int?, System.Data.CommandType?)' and 'Dapper.SqlMapper.QueryMultiple(System.Data.IDbConnection, string, dynamic, System.Data.IDbTransaction, int?, System.Data.CommandType?)'

and don't know how to properly solve this. The Dapper examples didn't mention such a problem and simply used QueryMultiple. I was able to circumvent the ambiguity using

var multi = con.QueryMultiple(new CommandDefinition(sql, new { id = 1 }))

But is that really necessary? Is there a better way?

like image 780
trenki Avatar asked Aug 25 '15 10:08

trenki


1 Answers

I bumped into the same problem after I added the package MiniProfiler.Providers.SqlServer, which depends on the Dapper.StrongName package, which depends on Dapper.

enter image description here

Obviously I didn't want to use the already referenced package of MiniProfiler, since it is always better to have control, like updating it when a new version is released.

The solution to resolving ambiguous code between assemblies is to assign an extern alias name/s to at least one of the assembly packages, so when you then want to refer to one of them, you can then specify which one you want to reference by using the alias name.

Here is the solution that worked for me:

To give an alias name to assembly Dapper.StrongName, I added the following to my .csproj file:

<Target Name="StrongNameAlias" BeforeTargets="FindReferenceAssembliesForReferences;ResolveReferences">
  <ItemGroup>
    <ReferencePath Condition="'%(FileName)' == 'Dapper.StrongName'">
      <Aliases>MP_DapperStrongNameAlias</Aliases>
    </ReferencePath>
 </ItemGroup>
</Target>

And then, if you'd want to refer to that, you can reference the assembly namespace by its newly added alies in .cs file, with the :: operator:

using MP_DapperStrongNameAlias::Dapper;

So now you can freely add using Dapper;, and it won't conflict anymore.

This Article might be helpful: C# 2.0: Using different versions of the same dll in one application

like image 146
Mayer Spitz Avatar answered Oct 05 '22 02:10

Mayer Spitz