我在实体框架核心映射方面遇到麻烦。 我收到此异常“不支持从'付款'到'Purchase.Payments'的关系,因为拥有实体类型'Purchase'不能位于非所有权关系的主体上。调试此功能的测试时。
你们可以帮我吗? :)
我尝试对这些映射进行一些更改,但仍然失败。
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");
}
}
答案 0 :(得分:0)
替换 builder.OwnsOne(x => x.Purchase).HasForeignKey(“ ShadowId”); 与 builder.HasOne(x => x.Purchase).HasForeignKey(“ ShadowId”);
´EF Core允许您对只能出现在其他实体类型的导航属性上的实体类型进行建模。这些称为拥有实体类型。包含拥有的实体类型的实体是其所有者。
https://docs.microsoft.com/en-us/ef/core/modeling/owned-entities