Tony Tony - 29 days ago 10
C# Question

npoco.Insert<T> fails on table withOUT AutoIncrement Primary key

I have an issue using the 'Insert of T' method of nPoco with a MySQL table defined like:

CREATE TABLE `TestTable` (
`Id` INT(11) NOT NULL,
`StatusEnum` INT(11) NOT NULL,

Database.Entity defined as...

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

public Status StatusEnum { get; set; } = Status.Default;

Code snippet:

// this works
var foo = new TestTable { Id = 123 };
"insert into operations.TestTable (Id, StatusEnum) values (@0, @1)",

// this throws "Field 'Id' doesn't have a default value"
var foo2 = new TestTable { Id = 456 };

Looking at the SQL generated by nPoco for the two inserts, I see this (from my log file)...

SQL: insert into operations.TestTable (Id, StatusEnum) values (?0, ?1) -> ?0 [Int32] = "123" -> ?1 [Int32] = "1"
SQL: INSERT INTO operations.TestTable (`StatusEnum`) VALUES (?0); SELECT @@IDENTITY AS NewID; -> ?0 [Int32] = "1"

For the 'Insert of T' method, why does nPoco think the Id column is an identity column? Removing the 'PrimaryKey' attribute from the class definition doesn't help.

NOTE: This question is similar to this question, but it might be slightly different.


Try changing your Primary Key definition to

[PrimaryKey("Id", AutoIncrement=false)]