2021-04-07
ValueObject as Entity ID, EntityTypeConfiguration Sample
markdown
問題:https://stackoverflow.com/questions/53328201/ef-core-non-primitive-type-value-object-as-primary-key
參考來源:https://github.com/dotnet/efcore/issues/13669
```
public class User
{
public UserId Id { get; set; }
public Credentials Credentials { get; set; }
}
public class UserId
{
private UserId()
{
}
private UserId(long id)
{
Id = id;
}
public long Id { get; private set; }
public static implicit operator long(UserId beaconId)
{
return beaconId.Id;
}
public static implicit operator UserId(long id)
{
return new UserId(id);
}
public override bool Equals(object obj)
{
if (obj == null)
{
return false;
}
var userId = (UserId) obj;
return this.Id == userId.Id;
}
public override int GetHashCode()
{
return Id.GetHashCode();
}
}
public class TestDbContext: DbContext
{
public TestDbContext(DbContextOptions options): base(options)
{
}
public DbSet Users { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
var userModelBuilder = modelBuilder.Entity();
userModelBuilder.Property(x => x.Id).HasConversion(x => x.Id, value => new UserId(value)).HasColumnName("Id").IsRequired();
userModelBuilder.OwnsOne(x => x.Credentials, c =>
{
c.Property(x => x.Email);
c.Property(x => x.Password);
});
}
}
```
訂閱:
文章 (Atom)