Reading exactly one row from Linq-to-SQL

I want to reorganize some C # modules that read data from SQL Server 2008 through Linq-to-SQL. These stored procedures retrieve no more than one row because I am representing the full PK as parameters. Linq-to-SQL does not seem to know that a maximum of one row can be returned. As a result, the following code is run to get a single value or throw an exception:

var results = context.MyProcName(myParameter); foreach (var result in results) { return result.THeColumnINeed; } throw new Exception(string.Format("Value not found for parameter {0}", myParameter)); 

This code does its job, but it looks ugly. How can I do it better?

+4
source share
2 answers
 return context.MyProcName(myParameter).Single().THeColumnINeed; 
+11
source

Try the following:

return context.MyProcName(myParameter).First();

+1
source

All Articles