I'm using
<PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="7.0.8" />
I create a table in sqlitestudio:
CREATE TABLE Product
(
name TEXT,
price NUMERIC,
quantity NUMERIC,
productId INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL
);
I scaffold the db into code
public string? Name { get; set; }
public byte[]? Price { get; set; }
public byte[]? Quantity { get; set; }
public long ProductId { get; set; }
(I seem to have to amend my Price
and Quantity
attributes to decimal etc, but it still seems to 'work', so we get)
public string? Name { get; set; }
public decimal? Price { get; set; }
public decimal? Quantity { get; set; }
public long ProductId { get; set; }
I then have some code that adds a new record
var newProduct = new Product
{
Name = "New",
Price = 0,
Quantity = 0
};
await context!.Products.AddAsync(newProduct);
I can't set the primary key, because it's autogenerated by the database (I've been through this before with ADO.NET and earlier versions of EF with SQL Server).
But I get an error:
System.InvalidOperationException: The instance of entity type 'Product' cannot be tracked because another instance with the same key value for {'ProductId'} is already being tracked. When attaching existing entities, ensure that only one entity instance with a given key value is attached
And yeah, I completely get that, I've added a record with a primary key of 0 and there already is one.
So how am I supposed to add data? (I've done this sooo many times before with SQL Server, but somehow this was never a problem, I'm missing something - that I can't find).
My only workaround at the moment is to generate guids for primary keys, which I always find a bit ugly.