ASP.NET Core 2.2,无法确定由实体框架中的导航属性表示的关系

时间:2019-08-03 00:05:06

标签: c# asp.net-core entity-framework-core asp.net-core-2.2

我正在开发使用Entity Framework Core的ASP.NET Core 2.2应用程序。我在OrganismoTransito(父母)和RadicacionCuenta(许多)之间存在一对多的关系。以下是根据该问题编写的代码段。

实体类:

public partial class RadicacionCuenta
{
    public RadicacionCuenta()
    {
        PropietariosRadicacionesCtas = new HashSet<PropietarioRadicacionCta>();
    }

    public int Id { get; set; }
    public string Placa { get; set; }
    public int IdTipoVehiculo { get; set; }
    public int IdLinea { get; set; }
    public string Modelo { get; set; }
    public string Cilindraje { get; set; }
    public string Tonelaje { get; set; }
    public string Pasajeros { get; set; }
    public string Watts { get; set; }
    public DateTime FechaRegistro { get; set; }
    public DateTime FechaSistema { get; set; }
    public int IdOrganismoTransitoOrigen { get; set; }
    public string EstadoDocumento { get; set; }
    public string DocumentosFaltantes { get; set; }
    public string NumeroFolios { get; set; }
    public DateTime FechaDevolucion { get; set; }
    public string UsuarioDevuelve { get; set; }
    public string EstadoRegistro { get; set; }
    public string MotivoCancelacion { get; set; }
    public string TipoPublico { get; set; }
    public string ValorFactura { get; set; }
    public int IdOrganismoTransitoDestino { get; set; }

    public virtual OrganismoTransito IdOrganismoTransitoDestinoNavigation { get; set; }
    public virtual OrganismoTransito IdOrganismoTransitoOrigenNavigation { get; set; }
    public virtual ICollection<PropietarioRadicacionCta> PropietariosRadicacionesCtas { get; set; }
}

public partial class OrganismoTransito
{
    public OrganismoTransito()
    {
        Blindados = new HashSet<Blindado>();
        Concesionarios = new HashSet<Concesionario>();
        FilialesTransito = new HashSet<FilialTransito>();
        Limitaciones = new HashSet<Limitacion>();
        Polarizados = new HashSet<Polarizado>();
        RadicacionesCuentaIdOrganismoTransitoDestinoNavigations = new HashSet<RadicacionCuenta>();
        RadicacionesCuentaIdOrganismoTransitoOrigenNavigations = new HashSet<RadicacionCuenta>();
        Vehiculos = new HashSet<Vehiculo>();
    }

    public int Id { get; set; }
    public int IdDivisionPolitica { get; set; }
    public string Nombre { get; set; }
    public string Jurisdiccion { get; set; }
    public string Categoria { get; set; }
    public string Abreviatura { get; set; }
    public string DivipoAlterno { get; set; }
    public bool Activo { get; set; }

    public virtual DivisionPolitica IdDivisionPoliticaNavigation { get; set; }
    public virtual ICollection<Blindado> Blindados { get; set; }
    public virtual ICollection<Concesionario> Concesionarios { get; set; }
    public virtual ICollection<FilialTransito> FilialesTransito { get; set; }
    public virtual ICollection<Limitacion> Limitaciones { get; set; }
    public virtual ICollection<Polarizado> Polarizados { get; set; }
    public virtual ICollection<RadicacionCuenta> RadicacionesCuentaIdOrganismoTransitoDestinoNavigations { get; set; }
    public virtual ICollection<RadicacionCuenta> RadicacionesCuentaIdOrganismoTransitoOrigenNavigations { get; set; }
    public virtual ICollection<Vehiculo> Vehiculos { get; set; }
}

我在DbContext的{​​{1}}中使用了Fluent配置,我没有使用任何注释。这是代码:

OnModelCreating

当我尝试在Package Manager控制台中运行modelBuilder.Entity<RadicacionCuenta>(entity => { entity.ToTable("RadicacionesCuentas"); entity.Property(e => e.Cilindraje) .IsRequired() .HasMaxLength(10) .IsUnicode(false); entity.Property(e => e.DocumentosFaltantes) .HasMaxLength(250) .IsUnicode(false); entity.Property(e => e.EstadoDocumento) .IsRequired() .HasMaxLength(10) .IsUnicode(false); entity.Property(e => e.EstadoRegistro) .IsRequired() .HasMaxLength(10) .IsUnicode(false); entity.Property(e => e.FechaDevolucion).HasColumnType("datetime2(0)"); entity.Property(e => e.FechaRegistro).HasColumnType("datetime2(0)"); entity.Property(e => e.FechaSistema).HasColumnType("datetime2(0)"); entity.Property(e => e.Modelo) .IsRequired() .HasMaxLength(10) .IsUnicode(false); entity.Property(e => e.MotivoCancelacion) .IsRequired() .HasMaxLength(10) .IsUnicode(false); entity.Property(e => e.NumeroFolios) .IsRequired() .HasMaxLength(10) .IsUnicode(false); entity.Property(e => e.Pasajeros) .IsRequired() .HasMaxLength(10) .IsUnicode(false); entity.Property(e => e.Placa) .IsRequired() .HasMaxLength(10) .IsUnicode(false); entity.Property(e => e.TipoPublico) .IsRequired() .HasMaxLength(10) .IsUnicode(false); entity.Property(e => e.Tonelaje) .IsRequired() .HasMaxLength(10) .IsUnicode(false); entity.Property(e => e.UsuarioDevuelve) .IsRequired() .HasMaxLength(10) .IsUnicode(false); entity.Property(e => e.ValorFactura) .HasMaxLength(100) .IsUnicode(false); entity.Property(e => e.Watts) .IsRequired() .HasMaxLength(10) .IsUnicode(false); entity.HasOne(d => d.IdOrganismoTransitoDestinoNavigation) .WithMany(p => p.RadicacionesCuentaIdOrganismoTransitoDestinoNavigations) .HasForeignKey(d => d.IdOrganismoTransitoDestino) .OnDelete(DeleteBehavior.ClientSetNull) .HasConstraintName("FK_RadicaCuentas_OTransitoD"); entity.HasOne(d => d.IdOrganismoTransitoOrigenNavigation) .WithMany(p => p.RadicacionesCuentaIdOrganismoTransitoOrigenNavigations) .HasForeignKey(d => d.IdOrganismoTransitoOrigen) .OnDelete(DeleteBehavior.ClientSetNull) .HasConstraintName("FK_RadicaCuentas_OTransitoO"); }); 时,出现此错误:

Add-Migration
  

System.InvalidOperationException:无法确定类型为“ ICollection”的导航属性“ OrganismoTransito.RadicacionesCuentaIdOrganismoTransitoDestinoNavigations”所表示的关系。要么手动配置关系,要么使用“ [NotMapped]”属性或“ OnModelCreating”中的“ EntityTypeBuilder.Ignore”忽略此属性。

     

在Microsoft.EntityFrameworkCore.Metadata.Conventions.Internal.PropertyMappingValidationConvention.Apply(InternalModelBuilder modelBuilder)
  在Microsoft.EntityFrameworkCore.Metadata.Conventions.Internal.ConventionDispatcher.ImmediateConventionScope.OnModelBuilt(InternalModelBuilder modelBuilder)
  在Microsoft.EntityFrameworkCore.Metadata.Conventions.Internal.ConventionDispatcher.OnModelBuilt(InternalModelBuilder modelBuilder)      在Microsoft.EntityFrameworkCore.Metadata.Internal.Model.Validate()      在Microsoft.EntityFrameworkCore.ModelBuilder.FinalizeModel()      在Microsoft.EntityFrameworkCore.Infrastructure.ModelSource.CreateModel(DbContext上下文,IConventionSetBuilder ConventionSetBuilder,IModelValidator验证程序)      在Microsoft.EntityFrameworkCore.Infrastructure.ModelSource。<> c__DisplayClass5_0.b__1()      在System.Lazy Add-Migration InitialCreateVehiculosSchema -Context ApplicationDbContext -Project SicotX.Backend.EF -StartupProject SicotX -OutputDir Migrations 1.ExecutionAndPublication(LazyHelper执行AndPublication,布尔值useDefaultConstructor)处      在System.Lazy 1.ViaFactory(LazyThreadSafetyMode mode) at System.Lazy 2.VisitCallSite(IServiceCallSite callSite,TArgument参数)处      在Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitScoped(ScopedCallSite scopedCallSite,ServiceProviderEngineScope范围)      在Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor 1.CreateValue() at Microsoft.EntityFrameworkCore.Infrastructure.ModelSource.GetModel(DbContext context, IConventionSetBuilder conventionSetBuilder, IModelValidator validator) at Microsoft.EntityFrameworkCore.Internal.DbContextServices.CreateModel() at Microsoft.EntityFrameworkCore.Internal.DbContextServices.get_Model() at Microsoft.EntityFrameworkCore.Infrastructure.EntityFrameworkServicesBuilder.<>c.<TryAddCoreServices>b__7_2(IServiceProvider p) at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitFactory(FactoryCallSite factoryCallSite, ServiceProviderEngineScope scope) at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor 2.VisitCallSite(IServiceCallSite callSite,TArgument参数)处      在Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitScoped(ScopedCallSite scopedCallSite,ServiceProviderEngineScope范围)      在Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor 2.VisitCallSite(IServiceCallSite callSite, TArgument argument) at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitConstructor(ConstructorCallSite constructorCallSite, ServiceProviderEngineScope scope) at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor 1访问器处)      在Microsoft.EntityFrameworkCore.Infrastructure.AccessorExtensions.GetService [TService](IInfrastructure 2.VisitCallSite(IServiceCallSite callSite, TArgument argument) at Microsoft.Extensions.DependencyInjection.ServiceLookup.DynamicServiceProviderEngine.<>c__DisplayClass1_0.<RealizeService>b__0(ServiceProviderEngineScope scope) at Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngine.GetService(Type serviceType, ServiceProviderEngineScope serviceProviderEngineScope) at Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngineScope.GetService(Type serviceType) at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService(IServiceProvider provider, Type serviceType) at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService[T](IServiceProvider provider) at Microsoft.EntityFrameworkCore.DbContext.get_DbContextDependencies() at Microsoft.EntityFrameworkCore.DbContext.get_InternalServiceProvider() at Microsoft.EntityFrameworkCore.DbContext.Microsoft.EntityFrameworkCore.Infrastructure.IInfrastructure<System.IServiceProvider>.get_Instance() at Microsoft.EntityFrameworkCore.Internal.InternalAccessorExtensions.GetService[TService](IInfrastructure 1工厂)      在Microsoft.EntityFrameworkCore.Design.Internal.DbContextOperations.CreateContext(String contextType)      在Microsoft.EntityFrameworkCore.Design.Internal.MigrationsOperations.AddMigration(字符串名称,字符串outputDir,字符串contextType)      在Microsoft.EntityFrameworkCore.Design.OperationExecutor.AddMigrationImpl(字符串名称,字符串outputDir,字符串contextType)      在Microsoft.EntityFrameworkCore.Design.OperationExecutor.AddMigration。<> c__DisplayClass0_1。<。ctor> b__0()      在Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase。<> c__DisplayClass3_0`1.b__0()      在Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.Execute(Action操作)   无法确定由“ ICollection”类型的导航属性“ OrganismoTransito.RadicacionesCuentaIdOrganismoTransitoDestinoNavigations”表示的关系。要么手动配置关系,要么使用“ [NotMapped]”属性或“ OnModelCreating”中的“ EntityTypeBuilder.Ignore”忽略此属性。

我需要帮助!谢谢

1 个答案:

答案 0 :(得分:0)

您需要使用“显式加载”来加载相关数据。您没有发布lambda表达式查询,所以我使用您的表进行简单的lambda表达式查询。请尝试以下方法,您将从子表访问父表数据。

using (var context = new dbContext())
{
    var varOrg = context.OrganismoTransito
        .Single(b => b.Id == 1);   


    context.Entry(varOrg)
        .Reference(b => b.RadicacionesCuentaIdOrganismoTransitoDestinoNavigations)
        .Load();
}

有关更多信息,请阅读本文。 https://docs.microsoft.com/en-us/ef/core/querying/related-data#explicit-loading