OrmLite SaveAll with Preset id of 0 fails with duplicate key constraint

I’ve got some reference data classes I’m trying to seed using the SaveAll method (insert or updates), but it always fails saying the id of 0 is already used. My first entities id is 0, but that shouldn’t have any affect on SaveAll should it?

To test:

[Alias("Entities")]
public partial class Entity : IHasId<int> 
{
	public EntityType()
	{
	}

    [Alias("Id")]
    [Required]
    public int Id { get; set; }

    public string Name { get; set; }

}

connection.SaveAll(new[]{new Entity(){Id = 0, Name = "Test"}, new Entity(){Id = 1, Name = "Test2"}, new Entity(){Id = 2, Name = "Test3"});

The error:

"Violation of PRIMARY KEY constraint 'PK_dbo.Entities'. Cannot insert duplicate key in object 'dbo.Entities'. The duplicate key value is (0).\r\nThe statement has been terminated."

I can confirm the entity with id of 0 exists in the database, shouldn’t OrmLite just update it’s Name?

OrmLite assumes a Primary Key of 0 (i.e. default(int)) means no record exists and will try to Insert it. You can use Update/UpdateAll to force Updating an existing entity.

1 Like

Ok I understand, for some (odd) reason some of my seed data I initialized with an id of 0 (it was in the early days of this project I’m re-writing). In the case of migrations (seeding), I was using db.Save (which does an insert / update accordingly).

I just had to switch to doing it manually.