Wednesday, May 13, 2009

Returning a single row from stored procedure

The stored procedure in LINQ to SQL will return ISingleResult type by default. 

If the result returned is not going to be used as a DataSource and a loop / list with a capacity of 1 is not favourable, a solution might be to access a single rowset and map it to an Entity.

  1. In the dbml file, right-click the Data Function created for the stored procedure in the right pane and select "Properties".

  2. Change the Return Type from (Auto-generated Type) to the Table Class; which should be available in the drop down (e.g. ThisTable).

  3. Use the following method to access the first (and only) item in the result returned:
public static ThisTable GetUser(int uid)
{
      ThisTable myTable= new ThisTable();
     DataClasses1DataContext dataContext = new DataClasses1DataContext();
      ISingleResult result = dataContext.GetUser(uid);
      return result.ToList()[0];
}

No comments: