Created
July 11, 2012 14:38
-
-
Save kristopherjohnson/3090796 to your computer and use it in GitHub Desktop.
Entity Framework snippets
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
{ | |
// ... | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment