gpt4 book ai didi

c# - 在 LINQ 查询中将枚举转换为字符串时出错

转载 作者:行者123 更新时间:2023-11-30 15:01:12 24 4
gpt4 key购买 nike

我有以下查询,它使用的是 Entity Framework 。

Analytic firstSent = (from a in Repository.Query<Analytic>()
where a.EntityType == "Proposal" &&
a.EntityId == Program.ActiveProposal.Id &&
a.Marker == AnalyticMarker.EmailProposalUrl.ToString()
orderby a.TimestampUtc
select a).FirstOrDefault();

在运行时,我收到以下错误:

LINQ to Entities does not recognize the method 'System.String ToString()' method, and this method cannot be translated into a store expression.

a.Marker 是一个字符串列,AnalyticMarker.EmailProposalUrl 是一个枚举值,我想将该列与该枚举的名称进行比较。

我知道 SQL 不支持从枚举到字符串的转换,但为什么它不解析这个字符串的值,然后将结果字符串传递给 SQL?那应该工作得很好。

最佳答案

试试这个:

var emailProposalUrl = AnalyticMarker.EmailProposalUrl.ToString();
Analytic firstSent = (from a in Repository.Query<Analytic>()
where a.EntityType == "Proposal" &&
a.EntityId == Program.ActiveProposal.Id &&
a.Marker == emailProposalUrl
orderby a.TimestampUtc
select a).FirstOrDefault();

This other answer正在解释为什么这也可以工作的原因..

The problem arises because ToString() isn't really executed, it is turned into a MethodGroup and then parsed and translated to SQL. Since there is no ToString() equivalent, the expression fails.

关于c# - 在 LINQ 查询中将枚举转换为字符串时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14570557/

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