joi, 15 aprilie 2010

LINQ, InsertOnSubmit And SubmitChanges

I have been trying to learn LINQ (actually, trying is really an overstatement) and ASP.NET MVC and i came across a little problem that baffled me.
How do you insert a record in a database using LINQ?
The answer is very, very simple and one scenario to go is using InsertOnSubmit and then SubmitChanges.

Quick example:
First, create a database and then a table called Movie with the following structure:
 Ok, now create some LINQ to SQL classes based on the previously created table.
So you should have by now a .dbml that looks like this (actual class definitions in the dbml.cs file in your project):
The next thing is to insert the following code in your desired method:

Code:
          MovieDbDataContext dbContext = new MovieDbDataContext();
         dbContext.Movies.InsertOnSubmit(movie);
         dbContext.SubmitChanges();
where MovieDbDataContext is the name of the DataContext class generated by LINQ and movie holds the data you want to save in the database.
Easy, right? Just don't forget to fire up that SubmitOnChanges method after InsertOnSubmit
Cheers:)

Niciun comentariu:

Trimiteți un comentariu