Monday, February 21, 2011

ASP.NET MVC - getting started with Linq and SQL procedure

Today is my first day using ASP.NET MVC, and I'm finding it very intriguing. I only just started learning asp.net.

So basically I'm trying to call a procedure from an MSSQL database, and with it I need to send a paramater "PlaceID", which is an integer. This procedure basically just picks out a number of columns from different tables in the database. Here is the Linq to SQL code

The ultimate goal is to be able to retrieve all the information and return it as JSON with a function that will be available for a javascript.

I'm wondering what is the best way to proceed from here. I know I have to create a view, but I'm still unclear exactly on how I can call the procedure and make it store all the information. I could really use some help on this, some code examples would be excellent. I already wrote a C#.net function to convert a datatable to JSON using a stringbuilder, but I get the feeling there is a smarter way to do things.

Any help is very appreciated.

From stackoverflow
  • Might I suggest going through the NerdDinner.com example first. I really think that you may have started down the wrong road and it would be worth backing up and doing some review first. For one thing, you probably don't want to be mixing DataTables and LINQ, typically you'd work with strongly-typed models and have your data context/repository return IQueryable/IEnumerables of the model instead of a DataTable. For another, there is a controller method that is able to turn a model into JSON for you. Generally, you should need to write your own JSON serialization.

    cc0 : I'm going through the tutorial they've got there. It seems excellent. I'm just not quite sure how to deal with importing procedures rather than tables. It'd be great if I could get some help explaining how to go from there.
    tvanfosson : If your procedure has a schema that matches a table, then simply drag the procedure onto the table in the designer. If there is no matching schema, then I usually will create a view that returns the same schema as the procedure, add that view as an entity in the designer, then drag the procedure onto the view. Either of these two mechanisms will create a method on the DataContext that invokes the stored proc and returns elements of the appropriate type. In some circumstances -- say when it returns a count or nothing -- I think you can also simply add the procedure to the "methods" pane.

0 comments:

Post a Comment