I've trying to create a new foreign key in entity framework core 6 but I am getting the following error?
The types of the properties specified for the foreign key {'RoleId' : RoleId} on entity type 'SomeEntity' do not match the types of the properties in the principal key {'Id' : Guid} on entity type 'DbsRole'. Provide properties that use the same types in the same order.
How can I fix this via Fluent API without adding navigation properties to my entities as I am following DDD principles (bounded contexts etc)?
I thought the conversion handler would be sufficient but obviously not.
RoleId.cs
public record RoleId(Guid Value);
SomeEntity.cs
public class SomeEntity : Entity<Guid>, IAggregateRoot
{
public Guid Id {get; private set;} = null!;
public string Name { get; private set; } = null!;
public RoleId RoleId { get; private set; } = null!;
}
MyContext.cs
public partial class MyContext : IdentityDbContext<MyUser, MyRole, Guid>
{
public virtual DbSet<SomeEntity> SomeEntity { get; set; } = default!;
//... snip...
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
_ = modelBuilder.Ignore<RoleId>();
_ = modelBuilder.Entity<SomeEntity>(entity =>
{
_ = entity.HasKey(e => e.Id);
_ = entity.Property(e => e.Name)
.IsRequired();
_ = entity.HasIndex(e => e.Name);
_ = entity.Property(e => e.RoleId)
.IsRequired()
.HasConversion(x => x.Value, x => new RoleId(x));
_ = entity.HasOne<MyRole>()
.WithMany()
.IsRequired()
.HasForeignKey(p => p.RoleId);
});
}
}
MyUser.cs
public class MyUser : IdentityUser<Guid>
{
//... snip...
}
MyRole.cs
public class MyRole : IdentityRole<Guid>
{
// ...snip...
}
Regards
Kyle