码迷,mamicode.com
首页 > 其他好文 > 详细

EntityFramework Core 封装

时间:2016-09-27 11:42:18      阅读:512      评论:0      收藏:0      [点我收藏+]

标签:

public class EntityBaseRepository<T> : IEntityBaseRepository<T>

where T : class, IEntityBase, new()

{

private SchedulerContext _context;

#region Properties

public EntityBaseRepository(SchedulerContext context)

{

_context = context;

}

#endregion

public virtual IEnumerable<T> GetAll()

{

return _context.Set<T>().AsEnumerable();

}

public virtual int Count()

{

return _context.Set<T>().Count();

}

public virtual IEnumerable<T> AllIncluding(params Expression<Func<T, object>>[] includeProperties)

{

IQueryable<T> query = _context.Set<T>();

foreach (var includeProperty in includeProperties)

{

query = query.Include(includeProperty);

}

return query.AsEnumerable();

}

public T GetSingle(int id)

{

return _context.Set<T>().FirstOrDefault(x => x.Id == id);

}

public T GetSingle(Expression<Func<T, bool>> predicate)

{

return _context.Set<T>().FirstOrDefault(predicate);

}

public T GetSingle(Expression<Func<T, bool>> predicate, params Expression<Func<T, object>>[] includeProperties)

{

IQueryable<T> query = _context.Set<T>();

foreach (var includeProperty in includeProperties)

{

query = query.Include(includeProperty);

}

return query.Where(predicate).FirstOrDefault();

}

public virtual IEnumerable<T> FindBy(Expression<Func<T, bool>> predicate)

{

return _context.Set<T>().Where(predicate);

}

public virtual void Add(T entity)

{

EntityEntry dbEntityEntry = _context.Entry<T>(entity);

_context.Set<T>().Add(entity);

}

public virtual void Update(T entity)

{

EntityEntry dbEntityEntry = _context.Entry<T>(entity);

dbEntityEntry.State = EntityState.Modified;

}

public virtual void Delete(T entity)

{

EntityEntry dbEntityEntry = _context.Entry<T>(entity);

dbEntityEntry.State = EntityState.Deleted;

}

public virtual void DeleteWhere(Expression<Func<T, bool>> predicate)

{

IEnumerable<T> entities = _context.Set<T>().Where(predicate);

foreach(var entity in entities)

{

_context.Entry<T>(entity).State = EntityState.Deleted;

}

}

public virtual void Commit()

{

_context.SaveChanges();

}

}

EntityFramework Core 封装

标签:

原文地址:http://www.cnblogs.com/94cool/p/5912088.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!