我对Linq很新,我可以在任何地方找到多行数据读取示例(通过使用foreach()),但是读取单行数据的正确方法是什么?像经典的产品详细信息页面.
以下是我的尝试:
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();
Run Code Online (Sandbox Code Playgroud)
代码看起来不错,但是当我看到使用SQL Profiler生成的实际SQL表达式时,它让我很害怕!程序执行了四个Sql表达式,它们完全相同!
因为我从一行读了四列.我想我一定做错了,所以我想知道这样做的正确方法是什么?
谢谢!
System.InvalidOperationException
当序列中没有元素满足指定条件时,使用First()扩展方法将抛出.
如果使用FirstOrDefault()
扩展方法,则可以针对返回的对象进行测试,以查看它是否为null.
FirstOrDefault返回序列的第一个元素,如果序列不包含元素,则返回默认值; 在这种情况下,Product的默认值应为null.尝试访问此null对象的属性将抛出ArgumentNullException
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;
}
Run Code Online (Sandbox Code Playgroud)
此外,ToString()
如果您正确设置了对象模型,则不必强制转换每个属性.ProductName,ProductDescription等应该已经是一个字符串.
您获得4个单独的SQL查询的原因是因为每次调用q.First().<PropertyHere>
linq都会生成一个新的Query.
小智 5
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();
Run Code Online (Sandbox Code Playgroud)