gpt4 book ai didi

c# - .NET Core/EF Core 2.0 升级后急切加载 "No coercion operator is defined between types"

转载 作者:行者123 更新时间:2023-11-30 16:42:43 25 4
gpt4 key购买 nike

在 .NET Core 1.x 中,我们有一个如下所示的方法:

public async Task<(PaperRecord Component, PaperPointerRecord Pointer)> GetOneAsync(DbSet<PaperPointerRecord> paperPointerRecords,
int? paperId = null,
long? externalPaperId = null,
Expression<Func<PaperPointerRecord, bool>> filter = null)
{
var query = filter is null ? paperPointerRecords.AsQueryable() : paperPointerRecords.Where(filter);

if (paperId.HasValue)
query = query.Where(_ => _.PaperPointerId == paperId);

if (externalPaperId.HasValue)
query = query.Where(_ => _.ExternalId == externalPaperId);

var record = await query.Include(_ => _.Paper)
.ThenInclude(_ => _.PaperColors)
.Select(_ => new
{
PaperRecord = _.Paper,
PaperPointerRecord = _
})
.SingleOrDefaultAsync();

return !(record is null) ? (record.PaperRecord, record.PaperPointerRecord) : throw NewPaperRecordNotFoundException(paperId, externalPaperId);
}

这对我们非常有用。将整个项目升级到所有 .NET Core 2.0 和 EF Core 2.0 后,该方法抛出此异常:

System.InvalidOperationException occurred: No coercion operator is defined between types 'PaperPointerRecord' and 'PaperRecord'.

这个异常发生在这个 block 中:

var record = await query.Include(_ => _.Paper)
.ThenInclude(_ => _.PaperColors)
.Select(_ => new
{
PaperRecord = _.Paper,
PaperPointerRecord = _
})
.SingleOrDefaultAsync();

如果我删除预先加载并像这样设置它,那么错误就会消失,但我也没有得到预期的结果:

var record = await query.Select(_ => new
{
PaperRecord = _.Paper,
PaperPointerRecord = _
})
.SingleOrDefaultAsync();

我检查了 Microsoft Documentation为此,我没有看到那里显示任何表明我们在预加载方面做错了什么。

最佳答案

Include 在这种情况下没有用,因为您正在返回一个投影并且 Include 被忽略(阅读关于忽略的包含 here )。

如果“预期结果”是指您希望 record.PaperRecord.Paper 具有一个值,只需将其包含在您的投影中即可; EF 将建立关系。

new
{
PaperRecord = _.Paper,
PaperPointerRecord = _,
PaperColor = _.Paper.PaperColor,
}

关于c# - .NET Core/EF Core 2.0 升级后急切加载 "No coercion operator is defined between types",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46323562/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com