gpt4 book ai didi

c# - EF 3.1 : Overcome LINQ GroupBy SQL translation problem

转载 作者:行者123 更新时间:2023-12-05 07:14:29 25 4
gpt4 key购买 nike

<分区>

在 MS SQL Server 中,我有一个包含联系人调用历史记录的表(这是另一个表)。EF 访问的实体如下:

public partial class CallbackHistory
{
public int HistoryId { get; set; }
public int CompanyId { get; set; }
public int CallerId { get; set; }
public DateTime LastCallTimeStamp { get; set; }

public virtual CompanyDiary Caller { get; set; }
public virtual Company Company { get; set; }
}

public partial class CompanyDiary
{
public CompanyDiary()
{
DatiCallbackHistory = new HashSet<DatiCallbackHistory>();
}
public int CallerId { get; set; }
public string NickName { get; set; }
public string PhoneNumber { get; set; }
public string Email { get; set; }
public int CompanyId { get; set; }

public virtual Company Company { get; set; }
public virtual ICollection<CallbackHistory> CallbackHistory { get; set; }
}

我需要获取按日期降序排列的最近 5 次调用的列表。

不幸的是,我提出了以下无法转换为 SQL 的查询:

var historyOfCalls = await
context.CallbackHistoryDbSet
.Include(historyEntry => historyEntry.Caller)
.Where(historyEntry => historyEntry.CompanyId == companyId)
.GroupBy(s => s.Caller.PhoneNumber)
.Select(s => s.OrderByDescending(historyEntry => historyEntry.LastCallTimeStamp).FirstOrDefault())
.Take(5)
.AsNoTracking()
.ToListAsync(cancellationToken).ConfigureAwait(false);

这是我得到的错误:

System.AggregateException
HResult=0x80131500
Message=One or more errors occurred. (The LINQ expression '(GroupByShaperExpression:
KeySelector: (c.PhoneNumber),
ElementSelector:(EntityShaperExpression:
EntityType: CallbackHistory
ValueBufferExpression:
(ProjectionBindingExpression: EmptyProjectionMember)
IsNullable: False
)
)
.OrderByDescending(historyEntry => historyEntry.LastCallTimeStamp)' could not be translated. Either rewrite the query in a form that can be translated, or switch to client evaluation explicitly by inserting a call to either AsEnumerable(), AsAsyncEnumerable(), ToList(), or ToListAsync(). See https://go.microsoft.com/fwlink/?linkid=2101038 for more information.)
Source=System.Private.CoreLib

Inner Exception 1:
InvalidOperationException: The LINQ expression '(GroupByShaperExpression:
KeySelector: (c.PhoneNumber),
ElementSelector:(EntityShaperExpression:
EntityType: CallbackHistory
ValueBufferExpression:
(ProjectionBindingExpression: EmptyProjectionMember)
IsNullable: False
)
)
.OrderByDescending(historyEntry => historyEntry.LastCallTimeStamp)' could not be translated. Either rewrite the query in a form that can be translated, or switch to client evaluation explicitly by inserting a call to either AsEnumerable(), AsAsyncEnumerable(), ToList(), or ToListAsync(). See https://go.microsoft.com/fwlink/?linkid=2101038 for more information.

看来问题出在我对导航属性进行分组这一事实。

我可以重写此查询以使其可转换为 SQL 吗?

我不知道什么时候切换到 Linq to objects使用此查询因为我已经调用了 ToListAsync。我试图在查询中的 Select 之后移动它,但它没有编译

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