C# 无法将“System.Data.Linq.DataQuery`1[System.Int32]”类型的对象转换为“System.IConvertible”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/792412/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Unable to cast object of type 'System.Data.Linq.DataQuery`1[System.Int32]' to type 'System.IConvertible'
提问by Vicheanak
I'm trying to insert the data into my database which has 2 tables
我正在尝试将数据插入到我有 2 个表的数据库中
Products
(ProductID): 1
(IDNumber) : 200900110
(ProductName) : Pepsi
Order
(OrderID): 1 (Auto Increment by 1)
(ProductID):1
(Date): 1/1/2009
产品
(ProductID): 1
(IDNumber) : 200900110
(ProductName) : Pepsi
Order
(OrderID): 1 (Auto Increment by 1)
(ProductID):1
(Date): 1/1/2009
The code is this:
代码是这样的:
var db = new ProductOrder();
var idNum = from p in db.Product
where p.IDNumber == 200900110
select p.ProductID;
var order = new Order();
order.productID = Convert.ToInt32(idNum);
order.Date = DateTime.Now;
db.Order.InsertOnSubmit(nTime);
db.SubmitChanges();
After I run it gives me the error like this:
运行后,它给了我这样的错误:
Unable to cast object of type 'System.Data.Linq.DataQuery`1[System.Int32]' to type 'System.IConvertible'
无将“System.Data.Linq.DataQuery`1[System.Int32]”类型的对象转换为“System.IConvertible”
采纳答案by Ronald Wildenberg
Your query:
您的查询:
from p in db.Product
where p.IDNumber == 200900110
select p.ProductID
does not return a single result but a list of results. In your case this will be a list containing a single product id. You should modify it to this:
不返回单个结果,而是返回结果列表。在您的情况下,这将是一个包含单个产品 ID 的列表。您应该将其修改为:
(from p in db.Product
where p.IDNumber == 200900110
select p.ProductID).Single()
If you run your code in the debugger and you hover your mouse over the idNumvariable, you'll see that it is a DataQueryinstance.
如果您在调试器中运行代码并将鼠标悬停在idNum变量上,您将看到它是一个DataQuery实例。

