数据库优先的Core 3.1 EF 6:无法确定多对多关系

时间:2020-10-06 07:34:32

标签: entity-framework entity-framework-core asp.net-core-3.1 ef-core-3.1

我在Core 3.1中使用具有多对多关系的EF“数据库优先”存在问题。 有两个表:ResourcesAZEZ和AsezPoolFileStore 第三个表AsezPoolFileLink仅包含两列:idRes和idFile

该类的自动生成的代码:

 public partial class AsezPoolFileStore
    {
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
        public AsezPoolFileStore()
        {
            this.ResourcesAZEZs = new HashSet<ResourcesAZEZ>();
        }
    
        public int id { get; set; }
        public string fileId { get; set; }
        public string filePath { get; set; }
    
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
        public virtual ICollection<ResourcesAZEZ> ResourcesAZEZs { get; set; }
    }

public partial class ResourcesAZEZ
    {
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
        public ResourcesAZEZ()
        {
            this.AsezDictResLinks = new HashSet<AsezDictResLink>();
            this.AsezPoolFileStores = new HashSet<AsezPoolFileStore>();
        }
    
        public int id { get; set; }
        public string id_outer { get; set; }
        public string number_customer { get; set; }
        public string material_text_full { get; set; }
        public string mark { get; set; }
        public string requirements { get; set; }
        public string mark_main { get; set; }
        public string unit { get; set; }
        public Nullable<double> quantity { get; set; }
        public string producer_text { get; set; }
        public string delivery_date { get; set; }
        public Nullable<decimal> price { get; set; }
        public string currency { get; set; }
....
    
        public virtual AsezBSCatalog AsezBSCatalog { get; set; }
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
        public virtual ICollection<AsezDictResLink> AsezDictResLinks { get; set; }
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
        public virtual ICollection<AsezPoolFileStore> AsezPoolFileStores { get; set; }
    }

在model.edmx中:

          <EntitySetMapping Name="AsezPoolFileStore">
            <EntityTypeMapping TypeName="BCR_ASEZModel.AsezPoolFileStore">
              <MappingFragment StoreEntitySet="AsezPoolFileStore">
                <ScalarProperty Name="id" ColumnName="id" />
                <ScalarProperty Name="fileId" ColumnName="fileId" />
                <ScalarProperty Name="filePath" ColumnName="filePath" />
              </MappingFragment>
            </EntityTypeMapping>
          </EntitySetMapping>

<EntitySetMapping Name="ResourcesAZEZs">
            <EntityTypeMapping TypeName="BCR_ASEZModel.ResourcesAZEZ">
              <MappingFragment StoreEntitySet="ResourcesAZEZ">
                <ScalarProperty Name="winner_okved" ColumnName="winner_okved" />
                <ScalarProperty Name="winner_kpp" ColumnName="winner_kpp" />
                <ScalarProperty Name="winner_inn" ColumnName="winner_inn" />
                <ScalarProperty Name="winner_id_asez" ColumnName="winner_id_asez" />
                <ScalarProperty Name="okved2" ColumnName="okved2" />
                <ScalarProperty Name="okpd2" ColumnName="okpd2" />
                <ScalarProperty Name="dictId" ColumnName="dictId" />
                <ScalarProperty Name="numberpubl" ColumnName="numberpubl" />
                <ScalarProperty Name="previous_ppid" ColumnName="previous_ppid" />
                <ScalarProperty Name="number_cgg" ColumnName="number_cgg" />
...
                <ScalarProperty Name="id_outer" ColumnName="id_outer" />
                <ScalarProperty Name="id" ColumnName="id" />
              </MappingFragment>
            </EntityTypeMapping>
          </EntitySetMapping>


          <AssociationSetMapping Name="AsezPoolFileLink" TypeName="BCR_ASEZModel.AsezPoolFileLink" StoreEntitySet="AsezPoolFileLink">
            <EndProperty Name="ResourcesAZEZ">
              <ScalarProperty Name="id" ColumnName="idRes" />
            </EndProperty>
            <EndProperty Name="AsezPoolFileStore">
              <ScalarProperty Name="id" ColumnName="idFile" />
            </EndProperty>
          </AssociationSetMapping>

一切看上去都与article中的一样。 但是,由于某种原因,我遇到了错误:

System.InvalidOperationException HResult = 0x80131509消息=无法 确定导航属性表示的关系 类型的“ ResourcesAZEZ.AsezPoolFileStores” “ ICollection”。手动配置 关系,或使用“ [NotMapped]”忽略此属性 属性或使用“ OnModelCreating”中的“ EntityTypeBuilder.Ignore”。 来源= Microsoft.EntityFrameworkCore StackTrace:at Microsoft.EntityFrameworkCore.Infrastructure.ModelValidator.ValidatePropertyMapping(IModel 型号IDiagnosticsLogger 1 logger) at Microsoft.EntityFrameworkCore.Infrastructure.ModelValidator.Validate(IModel model, IDiagnosticsLogger 1记录程序) Microsoft.EntityFrameworkCore.Infrastructure.RelationalModelValidator.Validate(IModel 型号IDiagnosticsLogger 1 logger) at Npgsql.EntityFrameworkCore.PostgreSQL.Infrastructure.NpgsqlModelValidator.Validate(IModel model, IDiagnosticsLogger 1记录程序) Microsoft.EntityFrameworkCore.Metadata.Conventions.ValidatingConvention.ProcessModelFinalized(IConventionModelBuilder modelBuilder,IConventionContext 1 context) at Microsoft.EntityFrameworkCore.Metadata.Conventions.Internal.ConventionDispatcher.ImmediateConventionScope.OnModelFinalized(IConventionModelBuilder modelBuilder) at Microsoft.EntityFrameworkCore.Metadata.Conventions.Internal.ConventionDispatcher.OnModelFinalized(IConventionModelBuilder modelBuilder) at Microsoft.EntityFrameworkCore.Metadata.Internal.Model.FinalizeModel() at Microsoft.EntityFrameworkCore.ModelBuilder.FinalizeModel() at Microsoft.EntityFrameworkCore.Infrastructure.ModelSource.CreateModel(DbContext context, IConventionSetBuilder conventionSetBuilder) at Microsoft.EntityFrameworkCore.Infrastructure.ModelSource.GetModel(DbContext context, IConventionSetBuilder conventionSetBuilder) at Microsoft.EntityFrameworkCore.Internal.DbContextServices.CreateModel() at Microsoft.EntityFrameworkCore.Internal.DbContextServices.get_Model() at Microsoft.EntityFrameworkCore.Infrastructure.EntityFrameworkServicesBuilder.<>c.<TryAddCoreServices>b__7_3(IServiceProvider p) at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitFactory(FactoryCallSite factoryCallSite, RuntimeResolverContext context) at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor 2.VisitCallSiteMain(ServiceCallSite callSite,TArgument参数)位于 Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitCache(ServiceCallSite callSite,RuntimeResolverContext上下文,ServiceProviderEngineScope serviceProviderEngine,RuntimeResolverLock lockType)位于 Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitScopeCache(ServiceCallSite singletonCallSite,RuntimeResolverContext上下文),位于 Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor 2.VisitCallSite(ServiceCallSite callSite, TArgument argument) at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitConstructor(ConstructorCallSite constructorCallSite, RuntimeResolverContext context) at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor 2.VisitCallSiteMain(ServiceCallSite callSite,TArgument参数)位于 Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitCache(ServiceCallSite callSite,RuntimeResolverContext上下文,ServiceProviderEngineScope serviceProviderEngine,RuntimeResolverLock lockType)位于 Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitScopeCache(ServiceCallSite singletonCallSite,RuntimeResolverContext上下文),位于 Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor 2.VisitCallSite(ServiceCallSite callSite, TArgument argument) at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.Resolve(ServiceCallSite callSite, ServiceProviderEngineScope scope) 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.get_DbContextDependencies() at Microsoft.EntityFrameworkCore.DbContext.get_Model() at Microsoft.EntityFrameworkCore.Internal.InternalDbSet 1.get_EntityType() 在Microsoft.EntityFrameworkCore.Internal.InternalDbSet 1.CheckState() at Microsoft.EntityFrameworkCore.Internal.InternalDbSet 1.get_EntityQueryable() 在 Microsoft.EntityFrameworkCore.Internal.InternalDbSet 1.System.Linq.IQueryable.get_Provider() at System.Linq.Queryable.Select[TSource,TResult](IQueryable 1源, 表达式`1选择器)位于 KROSS_Core.BLL.ASEZ.GSResourcesAZEZ.GetFilterFieldValues(String C:\ Estimates Core \ KROSS中的entityName) Core \ BLL \ ASEZ \ GSResourcesAZEZ.cs:第1550行,网址为 KROSS_Core.Controllers.GlobalSearchAsezController.AsezFiltersRead(HttpContext 上下文)在C:\ Estimates Core \ KROSS中 Core \ Controllers \ GlobalSearchAsezController.cs:第489行位于 KROSS_Core.Controllers.GlobalSearchAsezController.Post()在 C:\ Estimates Core \ KROSS Core \ Controllers \ GlobalSearchAsezController.cs:第70行位于 Microsoft.Extensions.Internal.ObjectMethodExecutor.Execute(Object 目标,Object []参数)位于 Microsoft.AspNetCore.Mvc.Infrastructure.ActionMethodExecutor.SyncObjectResultExecutor.Execute(IActionResultTypeMapper 映射器,ObjectMethodExecutor执行器,对象控制器,Object [] 争论) Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker。 d.MoveNext()

我在做什么错?或如何重新配置​​关系以使其正常工作?还是可以在此数据库优先模型中添加[NotMapped]属性?感谢您的帮助!

1 个答案:

答案 0 :(得分:1)

EFCore中的

NM关系有些棘手。我看到您同时拥有ICollection<ResourcesAZEZ>的{​​{1}}属性和AsezPoolFileStore的{​​{1}}属性,因为您需要有一个“关系实体”,我猜这是{ {1}}。

因此,两个实体上都应有一个ICollection<AsezPoolFileStore>。稍后,您可以将这些实体映射到您的应用程序模型或域,并删除ResourcesAZEZ中间结构,以便最终拥有现在拥有的集合。或者,始终在两个实体之间(取决于您)使用“关系实体”。

关于您如何使用AsezPoolFileLink属性的问题,您可以这样做:

ICollection<AsezPoolFileLink>

这将使具有此属性的任何属性都不会被EFCore映射到数据库中的字段。

您可以通过创建AsezPoolFileLink的{​​{1}}方法的替代来使用[NotMapped]实现相同的功能,例如

[NotMapped]
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<ResourcesAZEZ> ResourcesAZEZs { get; set; }

有关使用efcore进行建模的官方文档,请参见https://docs.microsoft.com/en-us/ef/core/modeling/