Tony Tony - 2 months ago 15
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,
PRIMARY KEY (`Id`)
)


Database.Entity defined as...

[TableName("operations.TestTable")]
[PrimaryKey("Id")]
[ExplicitColumns]
public class TestTable
{
[Column]
public int Id { get; set; }

[Column]
public Status StatusEnum { get; set; } = Status.Default;
}


Code snippet:

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

// this throws "Field 'Id' doesn't have a default value"
var foo2 = new TestTable { Id = 456 };
database.Insert<TestTable>(foo2);


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.

Answer

Try changing your Primary Key definition to

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