LINQ没有给我正确的数据

时间:2013-12-09 17:34:29

标签: .net linq

以下SQL脚本从我的数据库返回2行:

SELECT ChaperoneID, Name 
FROM ChaperoneInfo 
WHERE ChaperoneID IN (SELECT ChaperoneID 
                      FROM ChaperoneMatches 
                      WHERE DriverID = '111')

以下LINQ代码为我提供了一个空列表:

...
private const string SQL_GET_CHAPERONES_NAME = "SELECT ChaperoneID, Name FROM ChaperoneInfo WHERE ChaperoneID IN (SELECT ChaperoneID FROM ChaperoneMatches WHERE DriverID = '{0}')";
    ....
public List<ChaperoneNames> GetChaperones(string driverID)
{
    List<ChaperoneNames> diList = new List<ChaperoneNames>();
    ISafeDataContext dc = new ISafeDataContext();

    try
    {
        string strSQL = SQL_GET_CHAPERONES_NAME;
        object[] objParameters = new object[] { driverID };
        diList = dc.ExecuteQuery<ChaperoneNames>(strSQL, objParameters).ToList();
    }
    catch (Exception ex)
    {
        EventLog.WriteEntry("iSafe", ex.StackTrace + "\n \n" + ex.Message);
    }

    return diList;
}

,其中

public class ChaperoneNames
{
        public string ChaperoneID { get; set; }
        public string Name { get; set; }
}

它是ChaperoneNames字段名称中的内容吗?

1 个答案:

答案 0 :(得分:1)

您的ExecuteQuery命令将尝试使用sql参数,这意味着您的行

private const string SQL_GET_CHAPERONES_NAME = "SELECT ChaperoneID, Name FROM ChaperoneInfo WHERE ChaperoneID IN (SELECT ChaperoneID FROM ChaperoneMatches WHERE DriverID = '{0}')";

将产生TSQL,类似

 DECLARE @p0 NVarChar(1000) = '111'
 SELECT ChaperoneID, Name FROM ChaperoneInfo WHERE ChaperoneID IN 
    (SELECT ChaperoneID FROM ChaperoneMatches WHERE DriverID = '@p0')"

您需要做的是删除引号,即

private const string SQL_GET_CHAPERONES_NAME = "SELECT ChaperoneID, Name FROM ChaperoneInfo WHERE ChaperoneID IN (SELECT ChaperoneID FROM ChaperoneMatches WHERE DriverID = {0})";

所以你的查询就像

 DECLARE @p0 NVarChar(1000) = '111'
 SELECT ChaperoneID, Name FROM ChaperoneInfo WHERE ChaperoneID IN 
    (SELECT ChaperoneID FROM ChaperoneMatches WHERE DriverID = @p0)"