C# EF Core 3.0使用SingleOrDefault时出现下一个错误

C# EF Core 3.0使用SingleOrDefault时出现下一个错误,c#,ef-core-3.0,C#,Ef Core 3.0,我阅读了不同的解决方案,并尝试了不同的实现,但没有任何结果。 使用不同的实现时,错误始终相同:“System.InvalidOperationException:枚举器无法移动NextAsync。” 这就是生成异常的地方 var portfolioTrades = await _context .Portfolios .Include(PortfolioEntityTypeConfiguration.TradesList) .SingleOrDefaultAs

我阅读了不同的解决方案,并尝试了不同的实现,但没有任何结果。 使用不同的实现时,错误始终相同:“System.InvalidOperationException:枚举器无法移动NextAsync。”

这就是生成异常的地方

var portfolioTrades = await _context
      .Portfolios
      .Include(PortfolioEntityTypeConfiguration.TradesList)
      .SingleOrDefaultAsync(x => x.id == id);
include的处理方式是

  builder.OwnsMany<Trade>(TradesList, x =>
            {
                x.WithOwner().HasForeignKey("portfolio_id");
                x.ToTable("product_trade", SchemaNames.Public);

                x.Property<TradeID>("id");
                x.Property<DateTimeOffset>("_date").HasColumnName("date");
                x.Property("_details").HasColumnName("details");
                x.Property<Guid>("_schemaId").HasColumnName("schema_id");

                x.HasKey(x => x.id);

            });
下面是实体

 public class Trade : Entity
{
    public TradeID id { get; private set; }

    private DateTimeOffset _date { get; set; }

    public JObject _details { get; set; }

    private Guid _schemaId { get; set; }

    private Trade()
    {
        id = new TradeID(Guid.NewGuid());
    }

    private Trade( DateTimeOffset date, string details, Guid schema_id)
    {
        id = new TradeID(Guid.NewGuid());
        _date = date;
        _schemaId = schema_id;
        _details = JsonConvert.DeserializeObject<JObject>(details);
    }

    internal static Trade Create(DateTimeOffset date, string details, Guid schema_id)
    {
        return new Trade(date, details, schema_id);
    }

}
公共类交易:实体
{
publictradeid id{get;private set;}
私有日期时间偏移量_日期{get;set;}
公共作业对象_详细信息{get;set;}
私有Guid_schemaId{get;set;}
私人贸易()
{
id=新的TradeID(Guid.NewGuid());
}
私人交易(DateTimeOffset日期、字符串详细信息、Guid架构\u id)
{
id=新的TradeID(Guid.NewGuid());
_日期=日期;
_schemaId=schema_id;
_details=JsonConvert.DeserializeObject(details);
}
内部静态交易创建(DateTimeOffset日期、字符串详细信息、Guid架构\u id)
{
返回新交易(日期、详细信息、模式id);
}
}
}

public类公文包:实体,IAggregateRoot
{
公共PortfolioID id{get;private set;}
私有字符串_name{get;set;}
私有字符串_end_client_name{get;set;}
私有字符串_说明{get;set;}
私人只读列表交易;
私人投资组合()
{
_交易=新列表();
}
}
//错误

System.InvalidOperationException: Enumerator failed to MoveNextAsync.
   at Microsoft.EntityFrameworkCore.Query.ShapedQueryCompilingExpressionVisitor.SingleOrDefaultAsync[TSource](IAsyncEnumerable`1 asyncEnumerable, CancellationToken cancellationToken)
   at Microsoft.EntityFrameworkCore.Query.ShapedQueryCompilingExpressionVisitor.SingleOrDefaultAsync[TSource](IAsyncEnumerable`1 asyncEnumerable, CancellationToken cancellationToken)
   at Rx.Products.Infrastructure.Domain.Portfolios.PortfolioRepository.GetByPortfolioIdAsync(PortfolioID id) in ....\PortfolioRepository.cs:line 37
   at Rx.Products.Application.Portfolios.CreateTrade.CreateTradeCommandHandler.Handle(CreateTradeCommand request, CancellationToken cancellationToken) in ...\CreateTradeCommandHandler.cs:line 19
   at MediatR.Pipeline.RequestPreProcessorBehavior`2.Handle(TRequest request, CancellationToken cancellationToken, RequestHandlerDelegate`1 next)
   at MediatR.Pipeline.RequestPostProcessorBehavior`2.Handle(TRequest request, CancellationToken cancellationToken, RequestHandlerDelegate`1 next)
   at Rx.Products.API.TradesController.RegisterCustomer(CreateTradeRequest new_trade) in ....\TradesController.cs:line 65
   at Microsoft.AspNetCore.Mvc.Infrastructure.ActionMethodExecutor.TaskOfIActionResultExecutor.Execute(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.<InvokeFilterPipelineAsync>g__Awaited|19_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)
   at Microsoft.AspNetCore.Routing.EndpointMiddleware.<Invoke>g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)
   at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
   at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)

HEADERS
=======
Accept: */*
Accept-Encoding: gzip, deflate, br
Connection: keep-alive
Content-Length: 726
Content-Type: application/json
Host: localhost:54315
User-Agent: PostmanRuntime/7.24.1
Postman-Token: 2aabfa69-9d5c-4637-9d48-02a713077235
System.InvalidOperationException:枚举器无法移动NextAsync。
位于Microsoft.EntityFrameworkCore.Query.ShapedQueryCompilingExpressionVisitor.SingleOrDefaultAsync[TSource](IAsyncEnumerable`1 asyncEnumerable,CancellationToken CancellationToken)
位于Microsoft.EntityFrameworkCore.Query.ShapedQueryCompilingExpressionVisitor.SingleOrDefaultAsync[TSource](IAsyncEnumerable`1 asyncEnumerable,CancellationToken CancellationToken)
位于..\PortfolioRepository.cs:第37行中的Rx.Products.Infrastructure.Domain.PortfolioRepository.getByPortfolioIdeAsync(PortfolioID id)
在…\CreateTradeCommandHandler.cs:第19行中的Rx.Products.Application.portfolions.CreateTrade.CreateTradeCommandHandler.Handle(CreateTradeCommand请求,CancellationToken CancellationToken)处
在MediatR.Pipeline.RequestPreProcessorBehavior`2.Handle处(TRequest请求、CancellationToken CancellationToken、RequestHandlerDelegate`1下一步)
在MediatR.Pipeline.RequestPostProcessorBehavior`2.Handle处(TRequest请求、CancellationToken取消令牌、RequestHandlerDelegate`1下一步)
在..\TradesController.cs中的Rx.Products.API.TradesController.RegisterCustomer(CreateTradeRequest new\u trade)处
位于Microsoft.AspNetCore.Mvc.Infrastructure.ActionMethodExecutor.TaskOfActionResultExecutor.Execute(IActionResultTypeMapper映射器、ObjectMethodExecutor执行器、对象控制器、对象[]参数)
在Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.g|u等待| 12_0(ControllerActionInvoker invoker,ValueTask`1 actionResultValueTask)
在Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.g_u等待| 10_0(ControllerActionInvoker invoker,Task lastTask,State next,Scope Scope,Object State,Boolean isCompleted)
位于Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Rethrow(ActionExecutedContextSealed上下文)
位于Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(状态和下一步、范围和范围、对象和状态、布尔值和isCompleted)
在Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.g_u等待| 13_0(ControllerActionInvoker invoker,Task lastTask,State next,Scope Scope,Object State,Boolean isCompleted)
在Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.g_|19_0(ResourceInvoker invoker、Task lastTask、State next、Scope Scope、Object State、Boolean isCompleted)
在Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.g|u waiting | 17|0(ResourceInvoker invoker,Task Task,IDisposable作用域)
位于Microsoft.AspNetCore.Routing.EndpointMiddleware.g_uwaitRequestTask | 6_0(端点、任务请求任务、ILogger记录器)
位于Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext上下文)
位于Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext上下文)
标题
=======
接受:*/*
接受编码:gzip,deflate,br
连接:保持活力
内容长度:726
内容类型:application/json
主机:本地主机:54315
用户代理:PostmanRuntime/7.24.1
邮递员代币:2aabfa69-9d5c-4637-9d48-02a713077235
结果将生成相同的错误。 谢谢你抽出时间

  • 我认为,拥有一个公共的
    投资组合.Trades
    属性,可以用于导航,并定义
    投资组合
    类和
    交易
    类之间的关系,这将真正帮助您
  • public类公文包:实体,IAggregateRoot
    {
    //上面定义的其他类成员。。。
    //关系的新公共导航属性。
    公共IReadOnlyList Trades=>\u Trades.AsReadOnly();
    }
    
  • 如果使用
    OwnsMany
    关系,则不需要在查询中使用
    .Include
    语句。如果使用
    具有多个
    关系,则需要使用
    .Include
    语句
  • 使用
    有许多
    包括

    builder.HasMany(port.Trades,x=>
    {
    //上面定义的其他配置代码。。。
    });
    var portfolioTrades=等待上下文
    .投资组合
    .Include(port=>port.Trades)
    .SingleOrDefaultAsync(port=>port.id==id);
    
    使用
    OwnsMany
    而不是
    Include

    builder.OwnsMany(port.Trades,x=>
    {
    //上面定义的其他配置代码。。。
    });
    var portfolioTrades=等待上下文
    .投资组合
    .SingleOrDefaultAsync(port=>port.id==id);
    
    使用
    public class Portfolio : Entity, IAggregateRoot
    {
        public PortfolioID id { get; private set; }
    
        private string _name { get; set; }
    
        private string _end_client_name { get; set; }
    
        private string _description { get; set; }
    
        private readonly List<Trade> _trades;
    
        private Portfolio()
        {
           _trades = new List<Trade>();
        }
    }
    
    System.InvalidOperationException: Enumerator failed to MoveNextAsync.
       at Microsoft.EntityFrameworkCore.Query.ShapedQueryCompilingExpressionVisitor.SingleOrDefaultAsync[TSource](IAsyncEnumerable`1 asyncEnumerable, CancellationToken cancellationToken)
       at Microsoft.EntityFrameworkCore.Query.ShapedQueryCompilingExpressionVisitor.SingleOrDefaultAsync[TSource](IAsyncEnumerable`1 asyncEnumerable, CancellationToken cancellationToken)
       at Rx.Products.Infrastructure.Domain.Portfolios.PortfolioRepository.GetByPortfolioIdAsync(PortfolioID id) in ....\PortfolioRepository.cs:line 37
       at Rx.Products.Application.Portfolios.CreateTrade.CreateTradeCommandHandler.Handle(CreateTradeCommand request, CancellationToken cancellationToken) in ...\CreateTradeCommandHandler.cs:line 19
       at MediatR.Pipeline.RequestPreProcessorBehavior`2.Handle(TRequest request, CancellationToken cancellationToken, RequestHandlerDelegate`1 next)
       at MediatR.Pipeline.RequestPostProcessorBehavior`2.Handle(TRequest request, CancellationToken cancellationToken, RequestHandlerDelegate`1 next)
       at Rx.Products.API.TradesController.RegisterCustomer(CreateTradeRequest new_trade) in ....\TradesController.cs:line 65
       at Microsoft.AspNetCore.Mvc.Infrastructure.ActionMethodExecutor.TaskOfIActionResultExecutor.Execute(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.<InvokeFilterPipelineAsync>g__Awaited|19_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
       at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)
       at Microsoft.AspNetCore.Routing.EndpointMiddleware.<Invoke>g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)
       at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
       at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)
    
    HEADERS
    =======
    Accept: */*
    Accept-Encoding: gzip, deflate, br
    Connection: keep-alive
    Content-Length: 726
    Content-Type: application/json
    Host: localhost:54315
    User-Agent: PostmanRuntime/7.24.1
    Postman-Token: 2aabfa69-9d5c-4637-9d48-02a713077235