Reading exactly one row from Linq-to-SQL
I want to refactor some C# modules that read data from SQL Server 2008 via Linq-to-SQL. These stored procedures fetch at most one row, because I am submitting the full PK as parameters. Apparently Linq-to-SQL is not aware that at most one row can be returned. As a result, the following code runs to get one value or throw an exception:
var results = context.MyProcName(myParameter);
foreach开发者_如何学Python (var result in results)
{
return result.THeColumnINeed;
}
throw new Exception(string.Format("Value not found for parameter {0}", myParameter));
This code get the job done, but it kinda looks ugly. How can I do it better?
return context.MyProcName(myParameter).Single().THeColumnINeed;
Try this:
return context.MyProcName(myParameter).First();
精彩评论