2022-09-08 08:04:32 -07:00

99 lines
2.2 KiB
C#

using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using Church.Net.DAL.Core;
namespace Church.Net.DAL.EF
{
public class RepositoryBase<T> : IRepository<T> where T : class
{
private ChurchNetContext db = null;
private DbSet<T> dbSet = null;
public void Dispose()
{
db?.Dispose();
}
public RepositoryBase(string connString)
{
InitializeConnectionString(connString);
}
public void InitializeConnectionString(string connString)
{
db = new ChurchNetContext(connString);
foreach (PropertyInfo propertyInfo in db.GetType().GetProperties())
{
if (propertyInfo.PropertyType == typeof(DbSet<T>))
{
dbSet = (DbSet<T>) propertyInfo.GetValue(db, null);
}
}
}
public void Add(T obj)
{
dbSet.Add(obj);
db.SaveChanges();
}
public void Edit(T obj)
{
dbSet.Attach(obj);
db.SaveChanges();
}
public void Delete(T obj)
{
dbSet.Remove(obj);
db.SaveChanges();
}
public void Attach(T obj)
{
throw new NotImplementedException();
}
public T GetSingle()
{
return dbSet.First();
}
public T GetSingle(Expression<Func<T, bool>> whereCondition)
{
return dbSet.Where(whereCondition).FirstOrDefault();
}
public IList<T> GetAll()
{
return dbSet.ToList();
}
public IList<T> GetAll(Expression<Func<T, bool>> whereCondition)
{
return dbSet.Where(whereCondition).ToList();
}
public IQueryable<T> GetQueryable()
{
return dbSet;
}
public IQueryable<T> GetQueryable(Expression<Func<T, bool>> whereCondition)
{
return dbSet.Where(whereCondition);
}
}
}