Reputation: 4350
I have a record that came from the follow linq query:
using (var context = new myEntities())
{
var record = (from d in context.Student select d).SingleOrDefault();
}
I typically assign a new value to the record like this:
record.Value = SomeNewValue;
then I would do a
context.SaveChanges;
this all works fine. My question is: How can I save the same record if I pass it to another function or if the record was returned from a function? I am looking for something like this:
context.SaveChanges(record);
Upvotes: 1
Views: 1193
Reputation: 3314
Do you mean that you have a class object to work with? If so:
myEntities.Student.AddObject(student); //Where student is of type Student
Or if you don't have one yet, create one on the fly:
myEntities.Student.AddObject(new Student()
{
Name = formData[Name],
GPA = GetGPA(),
Major = Convert.ToString(Major)
});
You still have to call SaveChanges
after this though.
Alternatively...
If you keep track of your objects and work with them outside of the context above, you could modify the accessors for your properties so that when you modify the property of an object it calls the SaveChanges()
method and commits your change. Just something to think about.
Further Reading Material: http://msdn.microsoft.com/en-us/library/bb738695.aspx
Upvotes: 0
Reputation: 16623
Maybe would do you like something like this:
static class Utilities
{
public static void SaveChanges( this MyEntity entity, Student record, Student SomeNewValue )
{
record.Value = SomeNewValue;
entity.SaveChanges;
}
}
So then you can call the function like here:
context.SaveChanges(record, SomeNewValue);
Upvotes: 0
Reputation: 7758
The operation which triggers your function in question should create and manage the context
. If it was an ASP.NET MVC app I'd encourage you to set up the context at the beginning of the request and call context.SaveChanges
when it was finished. In a winforms/WPF app, you may want to keep the context
around for the life of the application, and call context.SaveChanges()
after any action that could change data (like a button press).
Upvotes: 1