Primitive Obsession - Strongly typed int ID with auto increment

.net-core c# domain-driven-design entity-framework-core sql-server

Question

How to get a strongly typed Id...

public sealed class FileUploadId
{
    public int Value { get; }

    public FileUploadId(int value)
    {
        Value = value;
    }
}

...which is used within my FileUpload class...

public class FileUpload : EntityBase, IAggregateRoot
{
    private FileUpload() { /* Required by EF */ }

    public FileUpload(string name, string relativePath, FileUploadType type, string contentType, long? size = null)
    {
        /* Guard clauses... */

        Id = new FileUploadId(0);

        /* Other properties... */
    }

    public FileUploadId Id { get; }

    /* Other properties... */
}

...working with identity (int auto increment)?

I tried ValueGeneratedOnAdd()in my TypeConifiguration, but without success...

public class FileUploadTypeConfig : IEntityTypeConfiguration<FileUpload>
{
    public void Configure(EntityTypeBuilder<FileUpload> builder)
    {
        builder.HasKey(x => x.Id);
        builder.Property(x => x.Id).HasConversion(x => x.Value, x => new FileUploadId(x)).ValueGeneratedOnAdd();

        /* Other configurations... */
    }
}

I know there's another option with the HiLo algorithm. But I want to get it work with default int id increment. Is this possible in any way?

1
2
11/6/2019 7:19:53 AM

Popular Answer

I'd advise against letting EF deal with the strongly typed Id. It does not handle it well and there will be cases where it will try to filter things in memory.

But you can have both properties, one for EF queries, and one for everything else.

class FileUpload
{
    public int InternalId { get; private set; }
    public FileUploadId Id 
    {
        get { return new FileUploadId(InternalId); }
        set { InternalId = value.Value; }
    }
}

It's leaky, but it works.

0
11/10/2019 10:38:37 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow