将ValueGeneratedOnAdd与复杂类型一起使用



假设您有一个复杂的类型:

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);
}
}

如何使用此复杂类型作为Id来配置类型,例如

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

在ef核心的类型配置中?

例如,一种类型配置,如:

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);
}
}

将生成一个空Guid(未生成任何值(。

您有一个设置Value的构造函数。为了获得一个值,您需要设置一个如下所示的值。

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

或者你有一个空的构造函数

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);
}
}

这样你就可以像这个一样使用

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

相关内容

最新更新