vreksam/DAL/Repositories/RepositoryBase.cs

81 lines
2.1 KiB
C#
Raw Permalink Normal View History

2017-06-12 13:37:48 +03:00
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Linq.Expressions;
using DAL.Interfaces;
namespace DAL.Repositories
{
public class RepositoryBase<T> where T : class
{
protected DbContext RepositoryDataContext;
protected DbSet<T> RepositoryDbSet;
public RepositoryBase(IFoorumDbContext dbContext)
{
RepositoryDataContext = dbContext as DbContext;
if (RepositoryDataContext == null)
{
throw new ArgumentNullException(paramName: nameof(dbContext));
}
RepositoryDbSet = RepositoryDataContext.Set<T>();
if (RepositoryDbSet == null)
{
throw new NullReferenceException(message: nameof(RepositoryDbSet));
}
}
public T Add(T entity)
{
var ret = RepositoryDbSet.Add(entity);
SaveChanges();
return ret;
}
public T Update(T entity)
{
RepositoryDbSet.Attach(entity);
RepositoryDataContext.Entry(entity).State = EntityState.Modified;
return entity;
}
public void Delete(T entity)
{
RepositoryDbSet.Remove(entity);
}
public void Delete(Expression<Func<T, bool>> where)
{
IEnumerable<T> objects = RepositoryDbSet.Where<T>(where).AsEnumerable();
foreach (T obj in objects)
RepositoryDbSet.Remove(obj);
}
public T GetById(int id)
{
return RepositoryDbSet.Find(id);
}
public virtual IEnumerable<T> GetAll()
{
return RepositoryDbSet.ToList();
}
public virtual IEnumerable<T> GetMany(Expression<Func<T, bool>> where)
{
return RepositoryDbSet.Where(where).ToList();
}
public T Get(Expression<Func<T, bool>> where)
{
return RepositoryDbSet.Where(where).FirstOrDefault<T>();
}
public int SaveChanges()
{
return RepositoryDataContext.SaveChanges();
}
}
}