在 EF Core 8 中执行插入时出现 NotSupportedException

问题描述 投票:0回答:1

我在使用 EF Core 8 时遇到问题,一种方法中有两个插入操作。我尝试向第一个表添加新记录,下一步是从另一个表获取数据,并将第三个数据插入到与第一个表相关的第三个表。

代码如下:

_context.Table1.Add(table1obj);
await _context.SaveChangesAsync(cancellationToken).ConfigureAwait(false);

var path = await _context.Database.SqlQuery<Table2Dto>($$"""
        SELECT...
    """)
    .ToListAsync(cancellationToken: cancellationToken).ConfigureAwait(false);

var table3obj = path.ConvertAll(x => new Table3
{
    Name = x.Name,
    OrderNumber = x.OrderNumber,
    Table1RefId = x.Id
});

_context.Table3.AddRange(table3obj);
await _context.SaveChangesAsync(cancellationToken: cancellationToken).ConfigureAwait(false);

Table1 的“SqlQuery()”和“Add()”工作正常,但对于 Table3 它显示:

System.NotSupportedException: Specified method is not supported.

全文错误:

System.NotSupportedException: Specified method is not supported.
   at System.Linq.ThrowHelper.ThrowNotSupportedException()
   at System.Linq.EmptyPartition`1.System.Collections.Generic.ICollection<TElement>.Add(TElement item)
   at Microsoft.EntityFrameworkCore.Metadata.Internal.ClrICollectionAccessor`3.AddStandalone(Object collection, Object value)
   at Microsoft.EntityFrameworkCore.Metadata.Internal.ClrICollectionAccessor`3.Add(Object entity, Object value, Boolean forMaterialization)
   at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.InternalEntityEntry.AddToCollection(INavigationBase navigationBase, Object 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, InternalEntityEntry duplicateEntry, Boolean fromQuery)
   at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.NavigationFixer.StateChanged(InternalEntityEntry entry, EntityState oldState, Boolean fromQuery)
   at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.InternalEntityEntryNotifier.StateChanged(InternalEntityEntry entry, EntityState oldState, Boolean fromQuery)
   at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.InternalEntityEntry.FireStateChanged(EntityState oldState)
   at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.InternalEntityEntry.SetEntityState(EntityState oldState, EntityState newState, Boolean acceptChanges, Boolean modifyProperties)
   at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.InternalEntityEntry.SetEntityState(EntityState entityState, Boolean acceptChanges, Boolean modifyProperties, Nullable`1 forceStateWhenUnknownKey, Nullable`1 fallbackState)
   at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.EntityGraphAttacher.PaintAction(EntityEntryGraphNode`1 node)
   at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.EntityEntryGraphIterator.TraverseGraph[TState](EntityEntryGraphNode`1 node, Func`2 handleNode)
   at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.EntityGraphAttacher.AttachGraph(InternalEntityEntry rootEntry, EntityState targetState, EntityState storeGeneratedWithKeySetTargetState, Boolean forceStateWhenUnknownKey)
   at Microsoft.EntityFrameworkCore.Internal.InternalDbSet`1.SetEntityState(InternalEntityEntry entry, EntityState entityState)
   at Microsoft.EntityFrameworkCore.Internal.InternalDbSet`1.SetEntityStates(IEnumerable`1 entities, EntityState entityState)
   at Microsoft.EntityFrameworkCore.Internal.InternalDbSet`1.AddRange(IEnumerable`1 entities)
   at WebSTapp.Server.Repositories.Activities.ActivityRepository.AddPathToActivity(ActivityAssignment asss, String activityId, String dataAreaId, Int32 assignmentId, CancellationToken cancellationToken) in D:\sources\WebST\WebST-v2\WebSTapp\Server\Repositories\Activities\ActivityRepository.cs:line 660
   at WebSTapp.Server.Services.Activities.ActivityService.CreateActivitiesAssignment(ActivitiesAssignmentRequest activitiesAssignmentDto, CancellationToken cancellationToken) in D:\sources\WebST\WebST-v2\WebSTapp\Server\Services\Activities\ActivityService.cs:line 263
   at WebSTapp.Server.Controllers.AssignmentsController.CreateAssignement(ActivitiesAssignmentRequest activitiesAssignmentDto) in D:\sources\WebST\WebST-v2\WebSTapp\Server\Controllers\AssignmentsController.cs:line 65
   at Microsoft.AspNetCore.Mvc.Infrastructure.ActionMethodExecutor.TaskOfIActionResultExecutor.Execute(ActionContext actionContext, IActionResultTypeMapper mapper, ObjectMethodExecutor executor, Object controller, Object[] arguments)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeActionMethodAsync>g__Awaited|12_0(ControllerActionInvoker invoker, ValueTask`1 actionResultValueTask)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeNextActionFilterAsync>g__Awaited|10_0(ControllerActionInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Rethrow(ActionExecutedContextSealed context)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeInnerFilterAsync>g__Awaited|13_0(ControllerActionInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeNextResourceFilter>g__Awaited|25_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResourceExecutedContextSealed context)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeFilterPipelineAsync>g__Awaited|20_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Logged|17_1(ResourceInvoker invoker)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Logged|17_1(ResourceInvoker invoker)
   at Microsoft.AspNetCore.Routing.EndpointMiddleware.<Invoke>g__AwaitRequestTask|7_0(Endpoint endpoint, Task requestTask, ILogger logger)
   at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
   at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)
   at Swashbuckle.AspNetCore.SwaggerUI.SwaggerUIMiddleware.Invoke(HttpContext httpContext)
   at Swashbuckle.AspNetCore.Swagger.SwaggerMiddleware.Invoke(HttpContext httpContext, ISwaggerProvider swaggerProvider)
   at Hellang.Middleware.ProblemDetails.ProblemDetailsMiddleware.Invoke(HttpContext context)
c# asp.net asp.net-web-api ef-core-8.0
1个回答
-1
投票

我没有解决这个问题,但我解决了它。我将此方法拆分为 2 个不同存储库中的 2 个方法。一种方法将数据添加到 Table1,第二种方法将数据添加到 Table3,并且有效!

但我不会放弃,我仍然会寻找问题。

编辑: 另一种解决方法:

让 EF core 通过将其添加到主表集合来添加列表。

var path = await _context.Database.SqlQuery<Table2Dto>($$"""
        SELECT...
    """)
    .ToListAsync(cancellationToken: cancellationToken).ConfigureAwait(false);

var table3obj = path.ConvertAll(x => new Table3
{
    Name = x.Name,
    OrderNumber = x.OrderNumber,
    Table1RefId = x.Id
});

table1obj.table3objList = table3obj;
_context.Table1.Add(table1obj);
await _context.SaveChangesAsync(cancellationToken).ConfigureAwait(false);
© www.soinside.com 2019 - 2024. All rights reserved.