正在将 WebApi 从 .net5 升级到 .net6。在名为“Order”的域实体的实体配置期间遇到了与 EF Core 6.0 相关的以下异常,该域实体与“ChargeItems”具有一对多关系:
System.InvalidOperationException HResult=0x80131509 Message=The object has been removed from the model. Source=Microsoft.EntityFrameworkCore StackTrace: at Microsoft.EntityFrameworkCore.Metadata.Internal.ForeignKey.get_Builder() at Microsoft.EntityFrameworkCore.Metadata.Internal.Navigation.OnAnnotationSet(String name, IConventionAnnotation annotation, IConventionAnnotation oldAnnotation) at Microsoft.EntityFrameworkCore.Infrastructure.ConventionAnnotatable.OnAnnotationSet(String name, Annotation annotation, Annotation oldAnnotation) at Microsoft.EntityFrameworkCore.Infrastructure.AnnotatableBase.SetAnnotation(String name, Annotation annotation, Annotation oldAnnotation) at Microsoft.EntityFrameworkCore.Infrastructure.ConventionAnnotatable.SetAnnotation(String name, Object value, ConfigurationSource configurationSource) at Microsoft.EntityFrameworkCore.Infrastructure.ConventionAnnotatable.SetOrRemoveAnnotation(String name, Object value, ConfigurationSource configurationSource) at Microsoft.EntityFrameworkCore.Metadata.Internal.PropertyBase.SetPropertyAccessMode(Nullable
1 propertyAccessMode, ConfigurationSource configurationSource) at Microsoft.EntityFrameworkCore.Metadata.Internal.PropertyBase.Microsoft.EntityFrameworkCore.Metadata.IMutablePropertyBase.SetPropertyAccessMode(Nullable
1 propertyAccessMode) at Eventec.Persistence.Core.Orders.OrderConfiguration.Configure(EntityTypeBuilder1 builder) in E:\Project\PersisentenceCore\Orders\OrderConfiguration.cs:line 101 at Microsoft.EntityFrameworkCore.ModelBuilder.ApplyConfiguration[TEntity](IEntityTypeConfiguration
1 configuration)
以下代码遇到此异常:
public class OrderConfiguration : IEntityTypeConfiguration<Order>
{
public void Configure(EntityTypeBuilder<Order> builder)
{
builder.ToTable("orders").HasKey(r => r.Id);
// other property config etc
// Charge Items
builder.HasMany(p => p.ChargeItems)
.WithOne()
.HasForeignKey("order_id")
.HasConstraintName("charge_items_order_id_fk")
.IsRequired()
.OnDelete(DeleteBehavior.Cascade)
.Metadata.PrincipalToDependent.SetPropertyAccessMode(PropertyAccessMode.Field);
}
}
无法通过使用 Google 等方式找到太多故障排除帮助。也没有任何有关 EF Core 6 的重大更改来解决此问题的信息。当然,它在 EF Core 5.x 上运行得很好。
最佳答案
新版本,新错误/重大更改。
请前往 EF Core GitHub Issue Tracker 填写问题/错误报告.
有问题的调用是
.Metadata.PrincipalToDependent.SetPropertyAccessMode(PropertyAccessMode.Field);
作为解决方法,可以完全删除它(它应该是默认设置),或者使用 EF Core 5.0 引入的 Navigation
Fluent API 进行配置:
builder.HasMany(p => p.ChargeItems)
.WithOne()
.HasForeignKey("order_id")
.HasConstraintName("charge_items_order_id_fk")
.IsRequired()
.OnDelete(DeleteBehavior.Cascade);
//.Metadata.PrincipalToDependent.SetPropertyAccessMode(PropertyAccessMode.Field);
builder.Navigation(p => p.ChargeItems)
.UsePropertyAccessMode(PropertyAccessMode.Field);
关于c# - EF Core 6.0 无效操作异常 : The object has been removed from the model,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69917518/