views:

2555

answers:

2

With LINQ-to-SQL in a ASP.NET MVC website I can display objects (records) from my database table.

Now I would like to create a new object and save it back to the database.

In my Controller, I do this:

    var dataContext = new MessageDataContext();
    Message message = new Message();
    message.Action = "save";
    message.Body = "record";
    message.Parameter = "234";

and now I want to SAVE it with something like this:

message.Save();

or perhaps:

dataContext.SubmitChanges(message);

but neither of these work.

What is the syntax here to:

  • add new objects and save them to the database
  • make changes on existing objects and save them to the database
+18  A: 

What you're looking for is:

dataContext.Messages.InsertOnSubmit(message);
dataContext.SubmitChanges();

Assuming you have a Messages table mapped into your Linq to SQL dbml.

HTH
Kev

Kev
+4  A: 

To add new objects just do:

dbContext.Messages.InsertOnSubmit(message);
dbContext.SubmitChanges();

If you make any changes to previously loaded entities just do:

dbContext.SubmitChanges();

If you don't want to submit any changed entity you need to do:

dbContext.Refresh(RefreshMode.OverwriteCurrentValues, message);
bruno conde