|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 |
using (MyEntities context = new MyEntities()) { // Query a collection IQueryable<MyThing> thingsQuery = from thing in context.Things where thing.Name == "Foo" select product; foreach (var t in thingsQuery) { DoSomethingWith(t); } // Delete an object context.DeleteObject(thingsQuery.First()); // Query for a single object, and process related objects var thing = context.Things.Include("Subthings").Where(o => o.ThingID.Equals("foo")).FirstOrDefault(); if (thing != null) { foreach (var subthing in thing.Subthings) DoSomethingWithSubthing(subthing); } // Save changes try { int count = context.SaveChanges(); } catch (OptimisticConcurrencyException) { context.Refresh(RefreshMode.ClientWins, things); context.SaveChanges(); } catch (UpdateException) { // ... } catch (InvalidOperationException) { // ... } } //Source: http://undefinedvalue.com/2012/07/11/entity-framework-cheatsheet |