0

我有以下异常。我检查了设计器,类和机会代码是一个 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; }
4

4 回答 4

4
 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 中不存在 Convert.ToInt32 之类的东西。

于 2013-06-05T10:15:21.127 回答
1

您可以通过首先执行转换然后查询数据库来轻松解决此问题:

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;
 }
于 2013-06-05T10:14:31.283 回答
1

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;
}
于 2013-06-05T10:16:43.333 回答
0

该方法在表达式中不起作用,因为它不能直接翻译成后备存储查询语言,但在此之前您可以很好地进行转换;先验地从字符串解析为整数,然后int在查询中使用本地定义的正确值。

在这样做时,我个人应该使用int.TryParse而不是Convert.ToInt32这样您可以更恰当地处理无效输入,而不是仅仅将结果放入表达式中。

于 2013-06-05T10:15:11.963 回答