andrewlock / StronglyTypedId

A Rosyln-powered generator for strongly-typed IDs
MIT License
1.52k stars 80 forks source link

[Question] Use with Db generated int Ids #72

Closed J0nnyI closed 9 months ago

J0nnyI commented 2 years ago

Is it possible to use this for primary key db-side value generation? Adding values always throws the following exception, which makes sense since I have to explicitly disable the value generation (link) image

is there a way to use db generated int value types? Something like .HasValueGenerator() looks like the right place to start but I was unable to find a way to create an id based on the existing entities or simple write back / convert the db generated value, which would be the preferred solution.

piotrbrzuska commented 2 years ago

@J0nnyI hello, have you dealt with this problem? I wrote a ValueGenerator that return temporary value of 0 or just default of StronglyTypedId. EF Core should skip this value and current value should by created using Identity in SQL Server.

    public class StronglyTypedIdValueGenerator<T> : ValueGenerator<T> where T : IEntityId
    {
        public override bool GeneratesTemporaryValues => true;

        public override T Next(EntityEntry entry)
        {
            return default;
        }
    }

 /// and then in EntityTypeConfiguration:
            builder.Property(o => o.Id)
            .ValueGeneratedOnAdd()
            .HasColumnType("int")
            .HasConversion(new ValueConverter<ProductId, int>(c => c.Value, c => new ProductId(c)))
            .HasValueGenerator<StronglyTypedIdValueGenerator<ProductId>>()
            .UseIdentityColumn();
J0nnyI commented 2 years ago

For reasons I have writable and read-only entity model variations of the same table in my application, ro-entities cant be added to the database. I solved this issue by using native types (int) on my writable entities and valuerypes on my read-only entities, since the issue only occurs when inserting data.

uladz-zubrycki commented 1 year ago

Question duplicates https://github.com/andrewlock/StronglyTypedId/issues/59.

Issue is resolved in EF Core 7, see https://github.com/andrewlock/StronglyTypedId/issues/59#issuecomment-1539753564

andrewlock commented 9 months ago

As described above, this should be solved in EF Core 7 🙂