Skip to content

Instantly share code, notes, and snippets.

@kristopherjohnson
Created July 11, 2012 14:38
Show Gist options
  • Save kristopherjohnson/3090796 to your computer and use it in GitHub Desktop.
Save kristopherjohnson/3090796 to your computer and use it in GitHub Desktop.
Entity Framework snippets
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