posts - 54, comments - 158, trackbacks - 4

My Links

Archives

Post Categories

Projects

Web Dev

LINQ, SQLMetal, MVC, CS1579

LINQ, SQLMetal, and MVC seem to complement each other extremely well. Together, the three lead to some very elegant and fast development. SQLMetal generates the database context for LINQ, which so happens to work as a great data layer/Model. The data context, complements of SQLMetal, can be place into the Model tier of MVC for convenient access by the Controllers. Using LINQ the data can be easily sent to the Views through the View Data. Very elegant.

Getting going using MVC and SQLMetal was fairly straight forward. The key was running the following from Visual Studio Command Line:

 

sqlmetal /server:SERVERNAME /database:DBNAME /code:DataContext.cs /language:csharp /views /functions /sprocs /namespace:Models /context:DataBase

 

I took the generated file, DataContext.cs and placed it into the Model folder. Now the database is immediately available through LINQ. For example to get all rows from a table "States" and pass to a view from the controller:

 

Models.DataBase db = new Models.DataBase("cnhere");

var states = from v in db.State select v;

return View(states);

 

Note that there is a tricky part, or atleast it was tricky for me. Make sure you define the type of data going to the view from the view's code behind like this:

 

public partial class State : ViewPage<IEnumerable<Models.State>>

 

Not doing this will result in errors like the following if you try to enumerate on ViewData.Model

 

Compilation Error

Description: An error occurred during the compilation of a resource required to service this request. Please review the following specific error details and modify your source code appropriately.

Compiler Error Message: CS1579: foreach statement cannot operate on variables of type 'object' because 'object' does not contain a public definition for 'GetEnumerator'

Print | posted on Saturday, June 07, 2008 11:06 PM | Filed Under [ Web Programming ]

kick it on DotNetKicks.com

Feedback

Gravatar

# re: LINQ, SQLMetal, MVC, CS1579

Thanks, it work fine!!
10/3/2008 7:44 PM | Cesar
Gravatar

# re: LINQ, SQLMetal, MVC, CS1579

Your Welcome!
10/4/2008 12:05 PM | CCook
Gravatar

# re: LINQ, SQLMetal, MVC, CS1579

Thanks.

Code behind really sucks though for ASP.NET MVC. A better way to create a strongly typed view is to use:

Inherits="System.Web.Mvc.ViewPage<[your app name].Models.[your table name]>"
5/12/2009 4:14 AM | Sam
Gravatar

# re: LINQ, SQLMetal, MVC, CS1579

Thanks Sam, I do agree.
5/14/2009 5:16 PM | CCook

Post Comment

Title  
Name  
Email
Url
Comment   
Please add 8 and 2 and type the answer here:

Powered by: