Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I insert data when the primary key column is not an identity column?

I'm trying to insert data using Dapper.Contrib, in a table where the primary key column is not an identity column.

The database table is created with this script:

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

This is the C# class:

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

    public string Name { get; set; }
}

When inserting data like this:

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

I get the following error:

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

Dapper correctly assumes, by convention, that Id is the primary key, but it incorrectly assumes that it is an identity column. How can I indicate that it is not an identity column?

like image 919
user247702 Avatar asked Oct 24 '16 11:10

user247702


People also ask

How can insert data without identity column in SQL Server?

If altering the table is not an option, you can try having a different table with the latest [misc_id] value inserted, so whenever you insert a new record into the table, you retrieve this value, add 1, and use it as your new Id. Just don't forget to update the table after.

Can an identity column not be a primary key?

In many cases an identity column is used as a primary key; however, this is not always the case. It is a common misconception that an identity column will enforce uniqueness; however, this is not the case. If you want to enforce uniqueness on the column you must include the appropriate constraint too.

Can we insert value in primary key column?

Rules for Primary Key Each table can have only one SQL Primary Key. All the values are unique and Primary key SQL value can uniquely identify each row. The system will not allow inserting a row with SQL Server Primary Key which already exists in the table.

How do you add an identity to an existing primary key column?

You can't alter the existing columns for identity. You have 2 options, Create a new table with identity & drop the existing table. Create a new column with identity & drop the existing column.


1 Answers

You can use the ExplicitKey attribute as per this issue.

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

    public string Name { get; set; }
}

Note that the return value is not the id of the inserted item as it usually is when you call Insert but is instead always 0.

like image 55
petelids Avatar answered Oct 27 '22 14:10

petelids