【发布时间】:2022-10-31 14:19:03
【问题描述】:
我想问你这个查询有什么问题。
public async Task<RecipeHeader> GetRecipeWithRecipeLineChild(int id)
{
try
{
return await dbSet.Where(x => x.RecipeHeaderId == id)
.Include(x => x.RecipeLines)
.ThenInclude(x => x.Unit)
.Include(x => x.CalculationMethod)
.ThenInclude(y => y.Calculation)
.FirstOrDefaultAsync();
}
catch (Exception ex)
{
_logger.LogError(ex, "{Repo} GetRecipeWithRecipeLineChild function error", typeof(RecipeHeaderRepository));
return new RecipeHeader();
}
}
当我使用.QueryString() 并复制到 AzureDataStudio 时,它可以工作。
但在我的应用程序中生成
2022-05-19 13:38:39.3178|10100|错误|Microsoft.EntityFrameworkCore.Query|迭代上下文类型“RecipesApi.Data.AppDbContext”的查询结果时发生异常。 System.Data.SqlTypes.SqlNullValueException:数据为空。不能对 Null 值调用此方法或属性。 在 lambda_method334(闭包,QueryContext,DbDataReader,ResultContext,SingleQueryResultCoordinator) 在 Microsoft.EntityFrameworkCore.Query.Internal.SingleQueryingEnumerable
1.Enumerator.MoveNext() System.Data.SqlTypes.SqlNullValueException: Data is Null. This method or property cannot be called on Null values. at lambda_method334(Closure , QueryContext , DbDataReader , ResultContext , SingleQueryResultCoordinator ) at Microsoft.EntityFrameworkCore.Query.Internal.SingleQueryingEnumerable1.Enumerator.MoveNext()这是Db模型
[Index(nameof(RecipeId),IsUnique =true)] public class RecipeHeader { [Key] public int RecipeHeaderId { get; set; } [MaxLength(15)] public string RecipeId { get; set; } [MaxLength(50)] public string RecipeName { get; set; } = ""; public int? CalculationMethodId { get; set; } [ForeignKey("CalculationMethodId")] public virtual CalculationMethod CalculationMethod { get; set; } [MaxLength(80)] public string Comment { get; set; } public int? PrescriptionId { get; set; } [ForeignKey("PrescriptionId")] public virtual Prescription Prescription { get; set; } public bool ColorRecipe { get; set; } public byte? Salt { get; set; } public byte? Program { get; set; } public ushort Version { get; set; } public DateTime CreatedDate { get; set; } public DateTime? UpdatedDate { get; set; } public string UpdatedBy { get; set; } = "system"; public bool Active { get; set; } public byte RecipeStatus { get; set; }= 1; public virtual ICollection<RecipeLine> RecipeLines { get; set; } }首先,我假设我的 ViewModel 和 AutoMapper 中有一些错误。所以我跳过 viewModel Automapper 等并使用 DB 模型但结果相同...... 现在我有点迷路了,我认为这将是一些愚蠢的小错误,但我看不到它...... 还有我的 dbTable 模式的打印屏幕
【问题讨论】:
-
抱歉我的错误已修复
-
你的模型有问题。 EF Core 不需要空字段,而是检索到 NULL。
-
您没有在查询中的任何地方使用 AutoMapper。该错误抱怨结果,而不是查询。在 EF Core 5 及更高版本中,如果为不可为空的属性返回
null值,则会引发错误,即使它是引用类型也是如此。例如,如果RecipeName为空,您将收到错误,因为类型是string,而不是string? -
为确保您不会收到此类错误,属性的可空性应映射表字段。这很烦人,因为在遇到
null之前不会出现任何编译或运行时错误。 -
顺便说一句,
RecipeName和Comment字段都可以为空,但属性是string而不是string?
标签: c# entity-framework-core automapper