Skip to content

Instantly share code, notes, and snippets.

@Chuhukon
Created Feb 17, 2014
Embed
What would you like to do?
Generic entity framework repository
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Data.Objects.DataClasses;
using System.Data.Objects;
using System.Data;
using System.Reflection;
namespace Koodr.Models.Repositories {
public abstract class BaseRepository<T> : IDisposable, IRepository<T> where T : EntityObject, new() {
internal ObjectContext _entities;
internal ObjectContext Entities {
get {
return _entities;
}
}
internal ObjectSet<T> ObjectSet;
internal string EntitySetName;
public BaseRepository(ObjectContext entities) {
_entities = entities;
ObjectSet = Entities.CreateObjectSet<T>();
EntitySetName = string.Format("{0}.{1}", ObjectSet.Context.DefaultContainerName, ObjectSet.EntitySet.Name);
}
public IQueryable<T> FindAll() {
return ObjectSet;
}
public IQueryable<T> FindAll(string[] includes) {
foreach (string incl in includes)
{
ObjectSet.Include(incl);
}
return ObjectSet;
}
public IQueryable<T> Find(Expression<Func<T, bool>> expr) {
return ObjectSet.Where(expr);
}
public T New() {
T entity = new T();
ObjectSet.AddObject(entity);
return entity;
}
public T FirstOrNew(Expression<Func<T, bool>> expr) {
var first = ObjectSet.FirstOrDefault(expr);
if (first == null) {
first = New();
}
return first;
}
public bool Contains(T entity, out T originalEntity) {
try {
object obj;
bool result = ObjectSet.Context.TryGetObjectByKey(EntityObjectHelper.GetEntityKey(entity, EntitySetName), out obj);
originalEntity = (T)obj;
return result;
}
catch (Exception ex) {
throw new ApplicationException(string.Format("Unknown exception while check contains: {0}", typeof(T).Name), ex);
}
}
public void Save(T entity) {
T original;
if (Contains(entity, out original)) {
//http://msdn.microsoft.com/en-us/library/dd283138.aspx
ObjectSet.ApplyCurrentValues(entity);
}
else {
ObjectSet.AddObject(entity);
}
}
public void CommitChanges() {
Entities.SaveChanges();
}
public void Dispose() {
_entities.Dispose();
GC.SuppressFinalize(this);
}
internal static EntityKey GetEntityKey(EntityObject entity, string entitySetName) {
PropertyInfo[] entityProperties = entity.GetType().GetProperties();
List<EntityKeyMember> keyList = new List<EntityKeyMember>();
foreach (PropertyInfo prop in entityProperties) {
object[] attrs = prop.GetCustomAttributes(false);
foreach (object obj in attrs) {
if (obj.GetType() == typeof(EdmScalarPropertyAttribute)) {
EdmScalarPropertyAttribute attr = (EdmScalarPropertyAttribute)obj;
if (attr.EntityKeyProperty) {
EntityKeyMember key = new EntityKeyMember { Key = prop.Name, Value = prop.GetValue(entity, null) };
keyList.Add(key);
}
}
}
}
return new EntityKey(entitySetName, keyList.AsEnumerable<EntityKeyMember>());
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment