gpt4 book ai didi

c# - 不支持从 _ 到 _ 的关系,因为拥有的实体类型 _ 不能位于非所有权关系的主体端

转载 作者:行者123 更新时间:2023-12-05 07:24:30 30 4
gpt4 key购买 nike

我在 Entity Framework 核心映射方面遇到了问题。我收到此异常“不支持从‘付款’到‘购买。付款’的关系,因为拥有的实体类型‘购买’不能位于非所有权关系的主要方面。”在调试此功能的测试时。

你们能帮我解决这个问题吗? :)

我已尝试对这些映射进行多项更改,但仍然失败。

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");
}
}

最佳答案

替换:

builder.OwnsOne(x => x.Purchase).HasForeignKey("ShadowId");

与:

 builder.HasOne(x => x.Purchase).HasForeignKey("ShadowId");

EF Core 允许您对只能出现在其他实体类型的导航属性上的实体类型进行建模。这些称为拥有的实体类型。包含拥有的实体类型的实体是其所有者。

https://learn.microsoft.com/en-us/ef/core/modeling/owned-entities

关于c# - 不支持从 _ 到 _ 的关系,因为拥有的实体类型 _ 不能位于非所有权关系的主体端,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55397362/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com