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:
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.
You can store any type of object in there, up to 2 GB in size.
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.
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With