Home ORMLite error on insert with autoincrement key
Reply: 1

ORMLite error on insert with autoincrement key

magicleon
1#
magicleon Published in 2018-01-12 15:45:29Z

I have the following MVC 5 Model:

[Schema("dbo")]
[Alias("map")]
public class Map {
    [PrimaryKey]
    [Alias("id")]
    public int Id { get; set; }

    [Alias("name")]
    public String Name { get; set; }

    //others

}

The id attribute on the table is a primary key autoincrement.

I need the Id to perform update operations but this prevents me to insert new entries.

This update works:

var res = dbConnection.Update<Map>(map);

While this insert does not:

var res = dbConnection.Insert<Map>(map, selectIdentity: true);

I get this exception:

Cannot insert explicit valuefor identity column in table 'map' when IDENTITY_INSERT is set to OFF.

What can I do to solve this?

CodeCaster
2#
CodeCaster Reply to 2018-01-12 16:12:09Z

The [AutoIncrement] attribute instructs ORMLite to omit the attributed field from the INSERT field list.

So apply it to the Id property:

[PrimaryKey]
[AutoIncrement]
[Alias("id")]
public int Id { get; set; }

And its value will be ignored when inserting or updating that entity.

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.315512 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO