Linq根据存储在SQL中的字符串返回单个整数值

时间:2012-01-20 10:43:39

标签: c# .net sql linq linq-to-sql

我对Linq很新,

我只是想做一个常规的返回,这通常是在SQL中完成的,似乎无法通过浏览数小时的浏览器获得直接的答案。

好的,我有一个表有两列的客户,CustomerID和CustomerName属于CustomersDataBase

我已经成功地使用以下方法(基本形式)从整数查询中返回单个字符串:

public string getCustomerName(int custID)
{
    CustomerDataBase cdb = new CustomerDataBase();

    string custName = (
        from c in cdb.Customers
        where c.CustomerID == custID
        select c.CustomerName)
        .SingleOrDefault();

    return custName;
}

好的,但是当我尝试通过尝试返回CustomerID来反转这种情况时,它会返回一个Exception:System.InvalidCastException:指定的强制转换是无效的。

这是我的代码:

public int getCustomerID(string custName)
{
    CustomerDataBase cdb = new CustomerDataBase();

    int custID = (
        from c in cdb.Customers
        where c.CustomerName == custName
        select c.CustomerID)
        .SingleOrDefault();

    return custID;
}

我也尝试过使用SQL术语来使custName字符串成为一个char数组:

public int getCustomerID(string custName)
{ 
    CustomerDataBase cdb = new CustomerDataBase();

    int custID = (
        from c in cdb.Customers
        where c.CustomerName == "'"+custName+"'"
        select c.CustomerID)
        .SingleOrDefault();

    return custID;
}

异常消失,但似乎只为CustomerID返回“0”,即使我有数百个条目。

所以在SQL中我只会使用以下内容:

Select CustomerID 
from   Customers 
where  CustomerName="'"+custName+"'"

任何帮助将不胜感激!感谢

//编辑代码使其正常工作(以下是Jon Skeet的回答): -

确定这有效:

[Table(Name =“TableCustomers”)]     公共类客户     {

    [Column(IsPrimaryKey = true, IsDbGenerated = true)]
    public long CustomerID { get; set; }
    [Column]
    public string CustomerName { get; set; }
    [Column]

} //用于在SQL数据库中使用BigInt

public long getCustomerID(string custName)         {

        CustomerDatabase cdb = new CustomerDatabase();



           long custID = (from c in cdb.Customers

                          where c.CustomerName == custName
                          select c.CustomerID).SingleOrDefault();

        return custID;
    }
}

1 个答案:

答案 0 :(得分:4)

您的最终方法肯定错误 - 您无需手动“引用”参数;基本上你正在搜索带引号的值,并且它从0返回SingleOrDefault,因为它没有找到条目。 (这就是SingleOrDefault所做的 - 如果没有结果,它会返回类型(int,此处)的默认值。)

怀疑您的CustomerID列可以为空,或者类似的东西 - 但是如果不了解您的架构,很难说清楚。您应该检查您的LINQ to SQL模型是否与您的数据库模式匹配。

如果有多个具有相同名称的客户,您应该考虑您想要发生什么 - 目前这将引发异常;这就是你想要的吗?

编辑:好的,现在你终于告诉我们架构有什么了,很清楚。 BigInt是一个64位整数,但您在LINQ模型中使用的是32位属性。只需将CustomerIDint更改为LINQ模型中的long,将方法更改为返回long,并且一切正常。