9

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?
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Edward Tanguay
  • 189,012
  • 314
  • 712
  • 1,047

2 Answers2

26

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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Kev
  • 118,037
  • 53
  • 300
  • 385
  • can I have a help with my problem please? [linked here](http://stackoverflow.com/questions/12761598/linq-to-sql-updates-datacontext-but-not-the-database) – Jed Oct 07 '12 at 11:57
  • the same action isn't supposet to be accomplish by dataContext.Messages.Attach(message) ??? – balanza May 15 '13 at 15:01
  • @balanza Quite possibly now, but back in 2009 probably not...I use Dapper now instead of LINQ (developed by the Stack team): https://code.google.com/p/dapper-dot-net/ so I've never kept up with LINQ developments. – Kev May 16 '13 at 00:30
9

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
  • 47,767
  • 15
  • 98
  • 117