将字符串转换为int时的特定linq异常.LINQ to Entities不能识别方法'm
本文关键字:识别 不能 Entities to 方法 LINQ 异常 int 转换 字符串 linq | 更新日期: 2023-09-27 18:16:55
我有以下例外。我检查了设计器和类,机会代码是int。
LINQ to Entities不能识别'Int32 ToInt32(System.Object)'方法,并且该方法不能转换为存储表达式
public tblOpportunity GetOpportunityByCode(string clientCode, string opportunityCode)
{
tblOpportunity opportunity = null;
ConnectionHandler.Invoke<EntityConnection>((connection) =>
{
var context = new xxEntities();
opportunity = context.tblOpportunities.FirstOrDefault<tblOpportunity>(o => o.ClientCode == clientCode && o.OpportunityCode == Convert.ToInt32(opportunityCode));
});
return opportunity;
}
}
public partial class tblOpportunity
{
public int OpportunityCode { get; set; }
public tblOpportunity GetOpportunityByCode(string clientCode, string opportunityCode)
{
tblOpportunity opportunity = null;
var convertedOpportunityCode = Convert.ToInt32(opportunityCode);
ConnectionHandler.Invoke<EntityConnection>((connection) =>
{
var context = new DMSEntities();
opportunity = context.tblOpportunities.FirstOrDefault<tblOpportunity>(o => o.ClientCode == clientCode && o.OpportunityCode == convertedOpportunityCode);
});
return opportunity;
}
应该可以了。你的问题是,实体框架不能转换成有效的sql表达式由于这样的事实,如转换。sql中不存在ToInt32
您可以通过首先执行转换,然后查询数据库来轻松解决这个问题:
public tblOpportunity GetOpportunityByCode(
string clientCode, string opportunityCode)
{
tblOpportunity opportunity = null;
var convertedOpportunityCode = Convert.ToInt32(opportunityCode);
ConnectionHandler.Invoke<EntityConnection>((connection) =>
{
var context = new xxEntities();
opportunity = context.tblOpportunities
.FirstOrDefault(o =>
o.ClientCode == clientCode &&
o.OpportunityCode == convertedOpportunityCode);
});
return opportunity;
}
LINQ告诉您的是它不实现将ToInt32
功能推到后端的功能。但是,您可以在自己的代码中执行此操作,而不会出现问题:
public tblOpportunity GetOpportunityByCode(string clientCode, string opportunityCode) {
tblOpportunity opportunity = null;
// Do the conversion outside LINQ
var opCodeInt = Convert.ToInt32(opportunityCode);
ConnectionHandler.Invoke<EntityConnection>((connection) => {
var context = new xxEntities();
opportunity = context.tblOpportunities.FirstOrDefault<tblOpportunity>(
o => o.ClientCode == clientCode && o.OpportunityCode == opCodeInt
); // ^^^^^^^^^
});
return opportunity;
}
该方法不能在表达式中工作,因为它不能直接翻译为后台存储查询语言,但是在此之前您可以很好地进行转换;先验地从字符串到整数进行解析,然后在查询中使用本地定义的int
。
在这样做时,我个人应该使用int.TryParse
而不是Convert.ToInt32
,以便您可以更适当地处理无效输入,而不是仅仅将结果扔到表达式中。