我有3张桌子,
Customer
、Program
和ProgramRegistrations
。客户是一个 IdentityUser 并在数据库 AspNetUsers 中。我的客户模型有一个 List<ProgramRegistration>
。 ProgramRegistrations 是一个包含 2 列(CustomerId 和 ProgramId)的表,它们构成了该表的复合 PK。
当我尝试保存新的
ProgramRegistration
时,出现以下错误:
The value of 'ProgramRegistrationEntity.CustomerId' is unknown when attempting to save changes. This is because the property is also part of a foreign key for which the principal entity in the relationship is not known.
在 ProgramRegistrationConfiguration 文件中我们创建密钥,
builder.HasKey(x => new {x.CustomerId, x.ProgramId});
在 CustomerConfiguration 文件中我有
builder.HasMany(x => x.ProgramRegistrations).WithOne(y => y.Customer).HasForeignKey(x => x.CustomerId);
我们正在从 EF Core 3 迁移到 EF Core 6,这对我们来说是一个症结所在。我不明白错误消息想告诉我什么。
根据您的描述,您的代码应如下所示
// Customer entity
public class Customer : IdentityUser
{
// Other properties of Customer
public List<ProgramRegistration> ProgramRegistrations { get; set; }
}
// Program entity
public class Program
{
public int ProgramId { get; set; }
// Other properties of Program
}
// ProgramRegistration entity
public class ProgramRegistration
{
public int CustomerId { get; set; }
public int ProgramId { get; set; }
// Other properties of ProgramRegistration
public Customer Customer { get; set; }
public Program Program { get; set; }
}
// CustomerConfiguration
public class CustomerConfiguration : IEntityTypeConfiguration<Customer>
{
public void Configure(EntityTypeBuilder<Customer> builder)
{
builder.HasMany(customer => customer.ProgramRegistrations)
.WithOne(programRegistration => programRegistration.Customer)
.HasForeignKey(programRegistration =>
programRegistration.CustomerId);
}
}
// ProgramRegistrationConfiguration
public class ProgramRegistrationConfiguration :
IEntityTypeConfiguration<ProgramRegistration>
{
public void Configure(EntityTypeBuilder<ProgramRegistration> builder)
{
builder.HasKey(programRegistration => new {
programRegistration.CustomerId, programRegistration.ProgramId });
}
}
并将以上配置注册到您的数据库上下文 onmodelcreating 事件
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
// Register configurations
modelBuilder.ApplyConfiguration(new CustomerConfiguration());
modelBuilder.ApplyConfiguration(new
ProgramRegistrationConfiguration());
// Other configurations
}