Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I save my object back into my database in LINQ to SQL?

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?
like image 910
Edward Tanguay Avatar asked Jan 09 '09 16:01

Edward Tanguay


People also ask

What is returned from a LINQ query?

Language-Integrated Query (LINQ) makes it easy to access database information and execute queries. By default, LINQ queries return a list of objects as an anonymous type. You can also specify that a query return a list of a specific type by using the Select clause.

Can we save object in database?

You can store any type of object in there, up to 2 GB in size.

Is LINQ converted to SQL?

LINQ to SQL offers an infrastructure (run-time) for the management of relational data as objects. It is a component of version 3.5 of the . NET Framework and ably does the translation of language-integrated queries of the object model into SQL. These queries are then sent to the database for the purpose of execution.


Video Answer


2 Answers

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.

like image 94
Kev Avatar answered Oct 13 '22 01:10

Kev


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);
like image 21
bruno conde Avatar answered Oct 13 '22 02:10

bruno conde