【问题标题】:'Collection is read-only.' when trying to initialise entities'集合是只读的。尝试初始化实体时
【发布时间】:2021-12-18 22:11:48
【问题描述】:

我只是想从数据库中获取我的实体:

var sendingRules = context.Set<SendingRules>().ToList();

但是自从我向SendingRules 添加了一个拥有的类型后,我收到了这个恼人的消息:

System.NotSupportedException: '集合是只读的。'

有问题的实体看起来像这样

public sealed class SendingRules : Entity<Guid>
{
    private readonly List<SendingRuleLBACFilter> _lbacFilters = new();

    private SendingRules() { }

    public SendingRules(LBACLevels? lbacLevel = null) : base(Guid.NewGuid())
    {
        LBACLevel = lbacLevel;
    }

    public LBACLevels? LBACLevel { get; private set; }

    public IReadOnlyCollection<SendingRuleLBACFilter> LBACFilters => _lbacFilters.AsReadOnly();

    public void AddLBACFilter(SendingRuleLBACFilter lbacFilter)
    {
        EnsureArg.IsNotNull(lbacFilter, nameof(lbacFilter));

        _lbacFilters.Add(lbacFilter);
    }
}

在哪里

public sealed class SendingRuleLBACFilter : SendingRuleFilter
{
    public SendingRuleLBACFilter(string template) : base(template)
    {
    }
}

这是我的流畅配置:

builder
    .OwnsMany(
        (sendingRule) => sendingRule.LBACFilters,
        (builder) =>
        {
            builder.ToTable("SendingRuleLBACFilters");
            builder.WithOwner()
                .HasForeignKey("SendingRulesId");
        });
        

我尝试在该配置调用的末尾添加.Navigation("_lbacFilters"),但随后它抱怨找不到该属性(即使在设置为公共之后...)

System.InvalidOperationException:找不到导航“SendingRules._lbacFilters”。请在配置实体类型前添加导航

有谁知道问题出在哪里?

at System.ThrowHelper.ThrowNotSupportedException(ExceptionResource resource)
at System.Collections.ObjectModel.ReadOnlyCollection`1.System.Collections.Generic.ICollection<T>.Add(T value)
at Microsoft.EntityFrameworkCore.Metadata.Internal.ClrICollectionAccessor`3.Add(Object entity, Object value, Boolean forMaterialization)
at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.InternalEntityEntry.AddToCollection(INavigationBase navigationBase, InternalEntityEntry value, Boolean forMaterialization)
at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.InternalMixedEntityEntry.AddToCollection(INavigationBase navigationBase, InternalEntityEntry value, Boolean forMaterialization)
at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.NavigationFixer.AddToCollection(InternalEntityEntry entry, INavigationBase navigation, InternalEntityEntry value, Boolean fromQuery)
at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.NavigationFixer.SetReferenceOrAddToCollection(InternalEntityEntry entry, INavigationBase navigation, InternalEntityEntry value, Boolean fromQuery)
at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.NavigationFixer.ToDependentFixup(InternalEntityEntry dependentEntry, InternalEntityEntry principalEntry, IForeignKey foreignKey, Boolean fromQuery)
at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.NavigationFixer.InitialFixup(InternalEntityEntry entry, Boolean fromQuery)
at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.NavigationFixer.TrackedFromQuery(InternalEntityEntry entry)
at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.InternalEntityEntryNotifier.TrackedFromQuery(InternalEntityEntry entry)
at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.InternalEntityEntry.MarkUnchangedFromQuery()
at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.StartTrackingFromQuery(IEntityType baseEntityType, Object entity, ValueBuffer& valueBuffer)
at Microsoft.EntityFrameworkCore.Query.QueryContext.StartTracking(IEntityType entityType, Object entity, ValueBuffer valueBuffer)
at Microsoft.EntityFrameworkCore.Query.RelationalShapedQueryCompilingExpressionVisitor.ShaperProcessingExpressionVisitor.<PopulateIncludeCollection>g__ProcessCurrentElementRow|60_0[TIncludingEntity,TIncludedEntity](<>c__DisplayClass60_0`2& )
at Microsoft.EntityFrameworkCore.Query.RelationalShapedQueryCompilingExpressionVisitor.ShaperProcessingExpressionVisitor.PopulateIncludeCollection[TIncludingEntity,TIncludedEntity](Int32 collectionId, QueryContext queryContext, DbDataReader dbDataReader, SingleQueryResultCoordinator resultCoordinator, Func`3 parentIdentifier, Func`3 outerIdentifier, Func`3 selfIdentifier, IReadOnlyList`1 parentIdentifierValueComparers, IReadOnlyList`1 outerIdentifierValueComparers, IReadOnlyList`1 selfIdentifierValueComparers, Func`5 innerShaper, INavigationBase inverseNavigation, Action`2 fixup, Boolean trackingQuery)
at Microsoft.EntityFrameworkCore.Query.Internal.SingleQueryingEnumerable`1.Enumerator.MoveNext()
at Microsoft.EntityFrameworkCore.DbContext.RemoveRange(IEnumerable`1 entities)
at Castle.Proxies.Invocations.DbContext_RemoveRange_1.InvokeMethodOnTarget()
at Castle.DynamicProxy.AbstractInvocation.Proceed()

__

我尝试将我的配置更改为这个

builder
    .OwnsMany<SendingRuleLBACFilter>(
        "_lbacFilters",
        builder =>
        {
            builder.ToTable("SendingRuleLBACFilters");
            builder.WithOwner()
                .HasForeignKey("SendingRulesId");
        }).Navigation(x => x.LBACFilters);

现在它给了我

无法确定“IReadOnlyCollection”类型的导航“SendingRules.LBACFilters”表示的关系。手动配置关系,或使用“[NotMapped]”属性或使用“OnModelCreating”中的“EntityTypeBuilder.Ignore”忽略此属性。

发生了什么事?

【问题讨论】:

    标签: c# entity-framework-core .net-5


    【解决方案1】:

    在将我的支持字段的名称更改为后,我得到了它的工作

    `_lBACFilters`
    

    但这太蹩脚了。如果有人有更好的解决方案,我不必有一个愚蠢的名字,我会接受你的回答

    【讨论】:

      猜你喜欢
      • 2011-10-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-14
      • 2023-01-23
      • 1970-01-01
      相关资源
      最近更新 更多