Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stored Procedures in LINQ-to-SQL

I have a stored procedure in a SQL Server database that returns a list of results. This stored procedure is exposed in the LINQ-to-SQL dbml file. I then try to call this stored procedure as such:

public List<MyObject> GetObjects()
{
  List<MyObject> objects = new List<MyObject>();
  using (DatabaseDataContext context = new DatabaseDataContext())
  {
    objects = context.GetObjectsFromDB();  // This is my problem line
  }
  return objects;
}

My problem is, I don't know how to convert the results of the stored procedure to a List<MyObject>. context.GetObjectsFromDB returns a System.Data.Linq.ISingleResult<sprocName>. How do I convert the result of the stored procedure to my List of strong pre-defined type?

Thank you!

like image 324
user208662 Avatar asked Jun 16 '11 13:06

user208662


People also ask

How LINQ queries converted into SQL queries?

LINQ to SQL translates the queries you write into equivalent SQL queries and sends them to the server for processing. More specifically, your application uses the LINQ to SQL API to request query execution. The LINQ to SQL provider then transforms the query into SQL text and delegates execution to the ADO provider.

Is LINQ converted to SQL?

LINQ to SQL offers an infrastructure (run-time) for the management of relational data as objects. It is a component of version 3.5 of the . NET Framework and ably does the translation of language-integrated queries of the object model into SQL. These queries are then sent to the database for the purpose of execution.

What you can do with LINQ to SQL?

LINQ to SQL supports all the key capabilities you would expect as a SQL developer. You can query for information, and insert, update, and delete information from tables.


1 Answers

Try this,

public List<MyObject> GetObjects()
{

 using (DatabaseDataContext context = new DatabaseDataContext())
 {
 var objects = context.GetObjectsFromDB();  
 return new  List<MyObject>(objects);
 }
}

Updated: By using explicit casting it can be done like this

public List<MyObject> GetObjects()
{  
 using (DatabaseDataContext context = new DatabaseDataContext())
 {
  List<MyObject> objects = (List<MyObject>)context.GetObjectsFromDB();  
  return objects;
 }
}
like image 140
Syeda Avatar answered Oct 30 '22 08:10

Syeda