Once my database was built, I created a new LINQ-enabled ASP.NET
web-site by selecting the LINQ template that is installed by the LINQ May CTP
within the “New Website” dialog in Visual
Web Developer (the free IDE for ASP.NET development). This sets up an
ASP.NET 2.0 project that has LINQ fully configured, and allows me to easily use
LINQ to connect against databases.
I then created a LINQ-enabled object model that I could use
to interact with the database defined above. The next release of Visual
Studio will provide a really nice WYSIWYG designer for creating and mapping
this database object model. In the meantime, I just used the command-line
“sqlmetal” utility that ships with LINQ to quickly create this. All I had
to-do was to open up a command-line console and type the following commands to
accomplish this:
Listing 1
>> cd c:\Program Files\LINQ Preview\Bin
>>
>> sqlmetal /database:PhotoDB /pluralize /namespace:PhotoAlbum /code:c:\Projects\PhotoApp\app_code\PhotoDB.cs
This created a LINQ-enabled object model for the “PhotoDB”
database on my local system and stored the generated classes within the
“PhotoDB.cs” file within the ASP.NET LINQ project. Note that the classes
generated are declared as “partial types” – meaning developers can optionally
add additional properties/methods to them in separate files (common scenarios:
entity validation or helper methods).
Once this LINQ-enabled object model is created, I can then
easily use this LINQ-enabled object model anywhere within my ASP.NET
application. For example, to create two new Albums in the Albums table I
could just write this code:
Listing 2
PhotoDB photoDb = new PhotoDB();
Album album1 = new Album();
album1.AlbumName = "Africa Trip";
Album album2 = new Album();
Album2.AlbumName = "Europe Trip";
photoDb.Albums.Add(album1);
photoDb.Albums.Add(album2);
photoDb.SubmitChanges();
When the "SubmitChanges()" method is called above,
the album instances above are saved into the SQL Server database within the
Albums table – without me having to write any raw SQL or data access
code. The above code is all that needed to be written for this to work.