When the PK column is not an identity column, how do I insert data with Dapper?

c# dapper dapper-contrib sql-server

Question

I'm attempting to use Dapper to insert data. Contrib, in a table when the identity column isn't the main key.

This script creates the database table:

begin transaction

create table
    dbo.Foos
    (
        Id int not null,
        Name nvarchar(max) not null
    )
go

alter table
    dbo.Foos
add constraint
    PK_Foos primary key clustered
    (
        Id
    )

go

commit

The C# class is this:

public class Foo
{
    public int Id { get; set; }

    public string Name { get; set; }
}

Whenever such data are inserted:

connection.Insert(new Foo()
{
    Id = 1,
    Name = "name 1"
});

I encounter the following issue:

Cannot insert the value NULL into column 'Id', table 'FooDatabase.dbo.Foos'; column does not allow nulls. INSERT fails.

By convention, Dapper is correct to assume thatId , however it mistakenly presumes that it is an identification column even though it is the main key. How can I make it clear that the column is not an identity column?

1
8
10/24/2016 11:54:45 AM

Accepted Answer

The may be used toExplicitKey property according to this problem

public class Foo
{
    [ExplicitKey]
    public int Id { get; set; }

    public string Name { get; set; }
}

As is customary when you call, the return value is not the id of the added item.Insert yet is always the opposite0 .

9
10/24/2016 12:14:10 PM


Related Questions





Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow