简体   繁体   中英

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.

尝试将主键定义更改为

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM