我遇到了实体框架核心映射的问题。 在调试这个功能的测试时,我遇到了异常'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.'。
你们能帮我解决一下吗? :)
虽然我尝试了几次更改这些映射,但仍然无法成功。
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");
}
}