Bulk Updates

(See Aggregates)

Not only can you use aggregate query functionality to retrieve data, you can also update data. If you want to update data without loading it, you can use the UpdateData static method on all entity collections. There is no need to load thousands of objects just to set a property on each and then persist. You data may be so big it does not fit into memory. In any case there is no need to load it in many cases. Simply update it with an expression.

The following code updates the CompanyName field of all Customers to the value of "New Company", where the existing value for City is ""Berlin.

Customer.UpdateData(x => x.CompanyName, x => x.City == "Berlin", "New Company");

You can make the where clause as complex as you wish. Keep in mind that every parameter in statement above is strongly-typed. Since we defined CompanyName as the field, the new value parameter is a string. You do not pass in an "object", but the actually typed parameter. The where expression is a LINQ expression so it is typed-checked as well. This is very important. If you modify your model and change CompanyName to integer for some reason, the compiler will tell you right away there is a problem. All model modifications are actually compiler checked, so you cannot deploy type errors to the field.

Implicit Table Joins

In another example, we can use a complex multi-table join as the where clause. Notice that there is no explicit join. The model defines the relationship. There is no need to know exactly how your database defined relations. If a property is in the Intellisense, you can use it. The following code actually joins Customer->Order->OrderDetail.

Customer.UpdateData(x => x.CompanyName,
	x => x.City == "Berlin" &&
	x.Order.OrderDetail.Discount < 20,
	"New Company");

Last edited May 8, 2012 at 12:40 PM by codetools, version 6


No comments yet.