I'm having trouble with the entity framework core mappings. I get this exception 'The relationship from 'Payment' to 'Purchase.Payments' is not supported because the owned entity type 'Purchase' cannot be on the principal side of a non-ownership relationship.' while debugging a test for this feature.
Can you guys help me with this? :)
I have tried to make several changes to these mappings but it continues to fail.
public class Car : Entity
{
public Purchase Purchase { get; private set; }
}
public class Purchase {
public List<Payment> Payments { get; private set; }
}
public class Payment : PaymentBase {
}
public abstract class PaymentBase : Entity {
public long CarId { get; protected set; }
public Car Car { get; protected set; }
public Purchase Purchase { get; private set; }
}
public class MyContext : DbContext {
public MyContext(DbContextOptions<MyContext> options) : base(options)
{
}
public DbSet<Car> Cars { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.ApplyConfiguration(new CarConfig());
modelBuilder.ApplyConfiguration(new PurchaseConfig());
modelBuilder.ApplyConfiguration(new PaymentConfig());
base.OnModelCreating(modelBuilder);
}
}
public class CarConfig : IEntityTypeConfiguration<Car>
{
public void Configure(EntityTypeBuilder<Car> builder)
{
builder.OwnsOne(x => x.Purchase).HasForeignKey("ShadowId");
builder.ToTable("CAR_DEALS");
builder.HasKey(x => x.Id);
builder.Property(x => x.Id).IsRequired().HasColumnName("CAR_ID");
}
}
public class PurchaseConfig : IEntityTypeConfiguration<Purchase>
{
public void Configure(EntityTypeBuilder<Purchase> builder)
{
builder.ToTable("CAR_DEALS");
builder.HasMany(x => x.Payments).WithOne();
}
}
public class PaymentConfig : IEntityTypeConfiguration<Payment>
{
public void Configure(EntityTypeBuilder<Payment> builder)
{
builder.ToTable("PAYMENTS");
builder.HasKey(x => x.Id);
builder.Property(x => x.Id).IsRequired().HasColumnName("PAYMENT_ID");
builder.HasOne(x => x.Purchase).WithMany(x => x.Payment);
builder.Ignore(x => x.Purchase);
builder.Property(x => x.CarId).HasColumnName("CAR_ID");
}
}