Skip to content

Dapper.Contrib [ExplicitKey] attribute behaves like the [Key] attribute when using with IDbConnection.InsertAsync() #53

Open
@DamienLaw

Description

@DamienLaw

I have a model

public class TestModel
{
    [ExplicitKey]
    public int ExplicitId1 { get; set; }

    [ExplicitKey]
    public int ExplicitId2 { get; set; }

    public int Property1 { get; set; }
}

When I performed a IDbConnection.InsertAsync(), everything is working as expected

var model = new TestModel
{
    ExplicitId1 = 1,
    ExplicitId2 = 2,
    Property1 = 3
};

await dbConnection.InsertAsync(model);
// The SQL Statement that is being generated:
// INSERT INTO Test (ExplicitId1, ExplicitId2, Property1) VALUES (@ExplicitId1, @ExplicitId2, @Property1)

Now, things start to go wrong when I performed an IDbConnection.UpdateAsync() first followed by an IDbConnection.InsertAsync().

if (!await dbConnection.UpdateAsync(model))
{
    await dbConnection.InsertAsync(model);
    // The SQL Statement that is being generated:
    // INSERT INTO Test (Property1) VALUES (@Property1)
}

The INSERT SQL Statement that is being generated has excluded the Properties decorated with the ExplicitKey attribute. The columns ExplicitId1 and ExplicitId2 are composite key in the database table which aren't auto generated but have to be supplied. An error will be thrown if the above INSERT statement is executed since the columns aren't provided.

I think I have located the source of the problem in the source file SqlMapperExtensions.Async.cs
The line keyProperties.AddRange(explicitKeyProperties); adds "Explicit Key Properties" into the list of "Key Properties" effectively treating ExplicitKeys as Keys and caching them for subsequent uses. Property decorated with the Key attribute is treated as an auto-generated column in the database table and hence excluded from the INSERT statement generated.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions