Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 (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?

like image 269
Arne Lund Avatar asked Dec 17 '22 13:12

Arne Lund


1 Answers

return context.MyProcName(myParameter).Single().THeColumnINeed;
like image 198
Marc Gravell Avatar answered Dec 27 '22 10:12

Marc Gravell