Skip to content

Interfaces as properties are not working as expected #1

@dittodhole

Description

@dittodhole

Hi there!

Following DTO given:

public interface IFoo { }
public sealed record FooA : IFoo { }
public sealed record FooB : IFoo { }

public sealed record DTO
{
  public int Id { get; set; }
  public IFoo? Foo { get; set; }
}

And the following query:

SqlMapper.AddTypeHandler(SqlMapper.StringTypeHandler<IFoo> _);

var dto = new DTO
{
  Foo = new FooA()
};

using var dbConnection = _;

dbConnection.Open();

var commandBuilder = dbConnection.CommandBuiler($@"
INSERT INTO [DTO] ([Id], [Foo])
VALUES (@Id, @Foo);");

commandBuilder.AddObjectProperties(dto);

commandBuilder.Execute();

Despite having a custom type handler registered, you'll end up with with:

System.NotSupportedException
  HResult=0x80131515
  Message=The member Foo of type FooA cannot be used as a parameter value
  Source=Dapper
  StackTrace:
   at Dapper.SqlMapper.LookupDbType(Type type, String name, Boolean demand, ITypeHandler& handler) in /_/Dapper/SqlMapper.cs:line 426

Executing this with the original ExecuteAsync works like a charm:

SqlMapper.AddTypeHandler(SqlMapper.StringTypeHandler<IFoo> _);

var dto = new DTO
{
  Foo = new FooA()
};

using var dbConnection = _;

dbConnection.Open();

dbConnection.Execute($@"
INSERT INTO [DTO] ([Id], [Foo])
VALUES (@Id, @Foo);",
  dto);

Any thoughts?

Best
Andreas

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or requesthelp wantedExtra attention is needed

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions