c# - 查询 DbSet 挂起/失败
问题描述
我有一个由 .NET Core 3.0、EF Core 3.0 提供支持并使用 MediatR 的 WebApi。它的两个域是Food
和FoodType
与它们对应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]
解决方案
推荐阅读
- python - 如何获取具有模块加载的bash文件?
- r - 在 R 中使用 barplot 的图例格式和放置
- python - 在 matplotlib 插图中调整轴标签和轴边界之间的间距
- python - 不要将鼠标悬停在元素上并单击(python selenium)
- java - Java中的随机for循环?
- node.js - 在 docker 容器中运行 npm install 时,Docker 节点服务返回 ECONNRESET 网络错误
- django - 如何为用户登录编写测试用例
- php - PHP 7.4+ 中的“在初始化之前不能访问类型属性”错误
- db2 - 使用 Db2 在 select 语句中调用存储过程
- azure - 无法使用 ansible 加密 Azure 存储帐户