posts - 81, comments - 262, trackbacks - 0

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 7, 2008 11:06 PM | Filed Under [ Web Programming ]

Powered by:
Powered By Subtext Powered By ASP.NET