Linq查询形成错误

时间:2015-08-07 10:07:40

标签: c# linq

获取错误 - >

  

LINQ to Entities无法识别方法'Int32   ToInt32(System.String)'方法,这个方法无法翻译   进入商店表达。

var checkcategory = from eqpCategory in db.rEqpCategories
                    join eqpType in db.rEqpTypes 
                    on eqpCategory.EqpTypeId equals eqpType.EqpTypeId 
                    join eqpGroup in db.rEqpGroups 
                    on eqpType.EqpGroupId equals eqpGroup.EqpGroupId 
                    where eqpCategory.EqpTypeId == int.Parse(cmbType.SelectedValue) 
                    && eqpCategory.EqpCategoryName == txtCategory.Text 
                    && eqpGroup.EqpGroupId == int.Parse(cmbGroup.SelectedValue)
                    select eqpCategory.EqpCategoryId;


if (checkcategory.Count() > 0)
{
    Page.ClientScript.RegisterClientScriptBlock(typeof(CMSUtility.TransferEquipments), 
                          "warning", 
                          "alert('Category Already present for same Group and Type');", 
                          true);
}

2 个答案:

答案 0 :(得分:4)

您不能在LINQ查询中使用int.Parse方法,因为它将尝试转换为数据库查询并将失败。在查询之前引入新变量。

int eqpTypeId = int.Parse(cmbType.SelectedValue);
int eqpGroupId = int.Parse(cmbGroup.SelectedValue);
var checkcategory = from eqpCategory in db.rEqpCategories
                    join eqpType in db.rEqpTypes
                    on eqpCategory.EqpTypeId equals eqpType.EqpTypeId
                    join eqpGroup in db.rEqpGroups
                    on eqpType.EqpGroupId equals eqpGroup.EqpGroupId
                    where eqpCategory.EqpTypeId == eqpTypeId &&
                          eqpCategory.EqpCategoryName == txtCategory.Text &&
                          eqpGroup.EqpGroupId == eqpGroupId
                    select eqpCategory.EqpCategoryId;

答案 1 :(得分:1)

不允许在EF Linq查询中运行int.Parse。试试这个

var id = int.Parse(cmbGroup.SelectedValue);
var checkcategory = from eqpCategory in db.rEqpCategories
                    join eqpType in db.rEqpTypes 
                         on eqpCategory.EqpTypeId equals      eqpType.EqpTypeId 
                    join eqpGroup in db.rEqpGroups 
                         on eqpType.EqpGroupId equals eqpGroup.EqpGroupId 
                    where eqpCategory.EqpTypeId == id 
                    && eqpCategory.EqpCategoryName == txtCategory.Text 
                    && eqpGroup.EqpGroupId == id
                    select eqpCategory.EqpCategoryId;

                    if (checkcategory.Count() > 0)
                    {
                        Page.ClientScript.RegisterClientScriptBlock(typeof(CMSUtility.TransferEquipments), "warning", "alert('Category Already present for same Group and Type');", true);
                    }