Skip to content

Instantly share code, notes, and snippets.

@sippylabs
Forked from Deathspike/Context.cs
Last active August 29, 2015 14:13
Show Gist options
  • Save sippylabs/b16ab9057980fad70e1b to your computer and use it in GitHub Desktop.
Save sippylabs/b16ab9057980fad70e1b to your computer and use it in GitHub Desktop.
Modified for EF5+
public class Context : IContext
{
public readonly ServiceEntities _entities;
#region Constructor
public Context()
{
_entities = new ServiceEntities();
}
#endregion
#region Implementation of IContext
public IMutableQuery<Category> Categories
{
get { return new MutableQueryable<Category>(_entities, _entities.Categories); }
}
public IMutableQuery<User> Users
{
get { return new MutableQueryable<User>(_entities, _entities.Users); }
}
public int SaveChanges()
{
return _entities.SaveChanges();
}
#endregion
}
public interface IContext
{
IMutableQuery<Category> Categories { get; }
IMutableQuery<User> Users { get; }
int SaveChanges();
}
public interface IMutableQuery<T> : IQueryable<T>
{
T Create(T item);
T Delete(T item);
T Update(T item);
}
public class MutableQueryable<T> : IMutableQuery<T> where T : class
{
private readonly ServiceEntities _entities;
private readonly IQueryable<T> _queryable;
#region Constructor
public MutableQueryable(ServiceEntities entities, IQueryable<T> queryable)
{
_entities = entities;
_queryable = queryable;
}
#endregion
#region Implementation of IEnumerable
public IEnumerator<T> GetEnumerator()
{
return _queryable.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
#endregion
#region Implementation of IMutableQuery<T>
public T Create(T item)
{
var objectSet = _entities.Set<T>();
objectSet.Add(item);
return item;
}
public T Delete(T item)
{
var objectSet = _entities.Set<T>();
objectSet.Remove(item);
return item;
}
public T Update(T item)
{
_entities.TryAddObject(item);
_entities.Entry(item).State = EntityState.Modified;
return item;
}
#endregion
#region Implementation of IQueryable
public Expression Expression
{
get { return _queryable.Expression; }
}
public Type ElementType
{
get { return _queryable.ElementType; }
}
public IQueryProvider Provider
{
get { return _queryable.Provider; }
}
#endregion
}
public static class ObjectContextExtensions
{
public static bool TryAddObject<T>(this DbContext context, T item) where T : class
{
try
{
context.Set<T>().Add(item);
return true;
}
catch (InvalidOperationException)
{
return false;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment