开发者

Reading exactly one row from Linq-to-SQL

开发者 https://www.devze.com 2023-03-11 07:38 出处:网络
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 Lin

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();

0

精彩评论

暂无评论...
验证码 换一张
取 消