首页 > 解决方案 > 查询 DbSet 挂起/失败

问题描述

我有一个由 .NET Core 3.0、EF Core 3.0 提供支持并使用 MediatR 的 WebApi。它的两个域是FoodFoodType与它们对应DataSet的 s,具有一对一的关系。执行下面的代码行挂起/失败(我不确定到底发生了什么,但它会跳转到return代码行)。请注意,查询Foods数据集工作得很好。另请注意,FoodTypes表中有记录。

public async Task<Unit> Handle(CreateFoodType request, CancellationToken cancellationToken)
{
     var foodType = await _context.FoodTypes.FirstOrDefaultAsync(type => type.Id == request.FoodTypeId);
     if (foodType == null)
          throw new Exception();

     //...bla bla bla

     return new Unit();
}

下面是代码/配置的片段。任何帮助,将不胜感激。

public class Food
{
     public Guid Id { get; set; }
     public int AverageWeight { get; set; }
     //...

     public virtual int FoodTypeId { get; set; }
     public virtual FoodType FoodType { get; set; }
}
public class FoodType
{
     public int Id { get; set; }
     public string Name { get; set; }

     public virtual Food Food { get; set; }
}

...和 ​​DBContext 类

public class DataContext : DbContext
{
     public DbSet<Food> Foods { get; set; }
     public DbSet<FoodType> FoodTypes { get; set; }

     public DataContext(DbContextOptions<DataContext> options) : base(options) { }

     protected override void OnModelCreating(ModelBuilder modelBuilder)
     {
         base.OnModelCreating(modelBuilder);

         modelBuilder.Entity<Food>()
            .HasOne(f => f.FoodType)
            .WithOne(ft => ft.Food)
            .HasForeignKey<Food>(f => f.FoodTypeId);
      }
}

编辑:添加异常堆栈跟踪:

   at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.OpenDbConnectionAsync(Boolean errorsExpected, CancellationToken cancellationToken)
   at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.OpenDbConnectionAsync(Boolean errorsExpected, CancellationToken cancellationToken)
   at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.OpenAsync(CancellationToken cancellationToken, Boolean errorsExpected)
   at Microsoft.EntityFrameworkCore.Storage.RelationalCommand.ExecuteReaderAsync(RelationalCommandParameterObject parameterObject, CancellationToken cancellationToken)
   at Microsoft.EntityFrameworkCore.Query.RelationalShapedQueryCompilingExpressionVisitor.AsyncQueryingEnumerable`1.AsyncEnumerator.MoveNextAsync()
   at Microsoft.EntityFrameworkCore.Query.ShapedQueryCompilingExpressionVisitor.FirstOrDefaultAsync[TSource](IAsyncEnumerable`1 asyncEnumerable, CancellationToken cancellationToken)
   at Microsoft.EntityFrameworkCore.Query.ShapedQueryCompilingExpressionVisitor.FirstOrDefaultAsync[TSource](IAsyncEnumerable`1 asyncEnumerable, CancellationToken cancellationToken)
   at Features.Foods.CreateFoodCommand.CreateRequestHandler.Handle(CreateFoodCommand request, CancellationToken cancellationToken) in [...redacted]

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

解决方案


推荐阅读