This project is read-only.

Persisting

Another problem area for developers is saving data back to the database. nHydrate removes this complication by handling all the chard issues for you. After selecting your data, you will most likely add, modify, or delete objects and want these changes to be persisted to store. Fortunately, the vast majority of the infrastructure to do this is generated. As described above, all objects are contained within a context. You can have any number of contexts loaded at any time; however they have no knowledge of each other. You can load one or more objects from one or more object types into a context. After making changes, simply call the SaveChanges method of the context to persist the changes. When calling the SaveChanges of a context the entire context is persisted. The further action is necessary for referential integrity.

using (var context = new NorthwindEntities())
{
	var customer = context.Customer.FirstOrDefault(x=>x.CustomerID == 1);
	customer.CompanyName = "Fred";
	context.SaveChanges();
}


The code above retrieves a Customer by primary key, modifies it, and saves it. After making any number of modifications you can finally save all the changes with one call in a SQL transaction. The entire modification graph will either succeed or fail.

using (var context = new NorthwindEntities())
{
	var customer = context.Customer.FirstOrDefault(x=>x.CustomerID == 1);
	customer.Name = "Fred";
	context.SaveChanges();

	//Add a new package to the collection
	var package = new Package();
	package.Customer = customer;
	package.Name = "MyNewPackage";
	context.AddItem(package);

	//Save the Customer and Packages in one transaction
	context.Persist();
}


In the code above, the final SaveChanges call saves the entire context. Also notice that all actions are strongly-typed. If you change the model to name

the Package object a Parcel object, the code above will not compile. You will know immediately that this must be corrected. This methodology is in stark

contrast to designs that specify a name in quotes which the compiler cannot check.

Last edited May 8, 2012 at 2:19 AM by codetools, version 7

Comments

No comments yet.