使用Linq to SQL读取单行数据的正确方法是什么?
我对Linq非常陌生,我可以在任何地方找到使用foreach读取多行数据的示例,但是读取单行数据的正确方法是什么?就像一个经典的产品细节页面 以下是我尝试过的:使用Linq to SQL读取单行数据的正确方法是什么?,linq,linq-to-sql,Linq,Linq To Sql,我对Linq非常陌生,我可以在任何地方找到使用foreach读取多行数据的示例,但是读取单行数据的正确方法是什么?就像一个经典的产品细节页面 以下是我尝试过的: var q = from c in db.Products where c.ProductId == ProductId select new { c.ProductName, c.ProductDescription, c.ProductPrice, c.ProductDate }; string strProduc
var q = from c in db.Products
where c.ProductId == ProductId
select new { c.ProductName, c.ProductDescription, c.ProductPrice, c.ProductDate };
string strProductName = q.First().ProductName.ToString();
string strProductDescription = q.First().ProductDescription.ToString();
string strProductPrice = q.First().ProductPrice.ToString();
string strProductDate = q.First().ProductDate.ToString();
代码在我看来很好,但当我看到使用SQL Profiler生成的实际SQL表达式时,我感到害怕!程序执行了四个Sql表达式,它们完全相同
因为我从一行读了四列。我想我一定是做错了什么,所以我想知道这样做的正确方法是什么
谢谢 当序列中没有元素满足指定条件时,使用第一个扩展方法将抛出System.InvalidOperationException
var q = (from c in db.Products
where c.ProductId == ProductId
select new { c.ProductName, c.ProductDescription, c.ProductPrice, c.ProductDate }
).First ();
string strProductName = q.ProductName.ToString();
string strProductDescription = q.ProductDescription.ToString();
string strProductPrice = q.ProductPrice.ToString();
string strProductDate = q.ProductDate.ToString();
如果使用FirstOrDefault扩展方法,则可以对返回的对象进行测试,以查看它是否为null
FirstOrDefault返回序列的第一个元素,如果序列不包含元素,则返回默认值;在这种情况下,产品的默认值应为null。尝试访问此null对象上的属性将引发ArgumentNullException
此外,如果您确定对象模型设置正确,则不必将每个属性强制转换为字符串。产品名称、产品描述等。。应该已经是一个字符串
之所以会得到4个单独的sql查询,是因为每次调用q.First时。linq正在生成一个新的查询。更新直觉的一种方法可能是:请注意,第一种方法是一个方法,而不是一个属性——这表明它将做一些事情。你只想做一次,所以只需先调用一次,如下面提到的,考虑FrimStRebug。对我来说,让我害怕的是不能在我的项目中使用LINQ。没有它我活不下去。
var q = (from c in db.Products
where c.ProductId == ProductId
select new { c.ProductName, c.ProductDescription, c.ProductPrice, c.ProductDate }).FirstOrDefault();
if (q != null)
{
string strProductName = q.ProductName;
string strProductDescription = q.ProductDescription;
string strProductPrice = q.ProductPrice;
string strProductDate = q.ProductDate;
}