Use ValueGeneratedOnAdd with complex type

106 Views Asked by At

Lets say you have a complex type:

public class Identity<TEntity> : IEquatable<Identity<TEntity>>
{
    public Identity(Guid value)
    {
        Value = value;
    }

    public Guid Value { get; }


    public static implicit operator Guid(Identity<TEntity> identity)
    {
        return identity.Value;
    }

    public static explicit operator Identity<TEntity>(Guid value)
    {
        return new Identity<TEntity>(value);
    }
}

How to configure a type using this complex type as Id, e.g.

public class MyEntity
{
    public Identity<TEntity> Id { get; }
}

within a type configuration for ef core?

For example a type configuration like:

public class MyEntityTypeConfiguration : IEntityTypeConfiguration<MyEntity>
{
    public void Configure(EntityTypeBuilder<MyEntity> builder)
    {
       var converter = new ValueConverter<Identity<MyEntity>, Guid>(
           v => v.Value,
           v => new Identity<MyEntity>(v));

       builder.HasKey(e => e.Id);
       builder.Property(e => e.Id)
           .ValueGeneratedOnAdd()
           .HasConversion(converter);
    }
}

will produce an empty Guid (no values generated).

1

There are 1 best solutions below

2
Vaduganathan On

You have a constructor which set the Value. In order to get a value you need to set a value like below.

Identity<Gibra> identity = new Identity<Gibra>(Guid.NewGuid());

Or you have a empty constructor

public class Identity<TEntity> : IEquatable<Identity<TEntity>>
{
    Guid _value = Guid.NewGuid();
    public Identity(Guid value)
    {
        Value = value;
    }

    public Identity()
    {
        
    }

    public Guid Value { get { return _value; } set { _value = value; } }

    public bool Equals(Identity<TEntity> other)
    {
        throw new NotImplementedException();
    }

    public static implicit operator Guid(Identity<TEntity> identity)
    {
        return identity.Value;
    }

    public static explicit operator Identity<TEntity>(Guid value)
    {
        return new Identity<TEntity>(value);
    }
}

So that you can use like this

Identity<Gibra> identity = new Identity<Gibra>();