Permalink
Switch branches/tags
Nothing to show
Find file Copy path
5948403 Oct 10, 2018
1 contributor

Users who have contributed to this file

102 lines (83 sloc) 2.43 KB
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using Microsoft.EntityFrameworkCore;
namespace Threenine.Data
{
public class Repository<T> : BaseRepository<T>, IRepository<T> where T : class
{
public Repository(DbContext context) : base(context)
{
}
public void Add(T entity)
{
_dbSet.Add(entity);
}
public void Add(params T[] entities)
{
_dbSet.AddRange(entities);
}
public void Add(IEnumerable<T> entities)
{
_dbSet.AddRange(entities);
}
public void Delete(T entity)
{
var existing = _dbSet.Find(entity);
if (existing != null) _dbSet.Remove(existing);
}
public void Delete(object id)
{
var typeInfo = typeof(T).GetTypeInfo();
var key = _dbContext.Model.FindEntityType(typeInfo).FindPrimaryKey().Properties.FirstOrDefault();
var property = typeInfo.GetProperty(key?.Name);
if (property != null)
{
var entity = Activator.CreateInstance<T>();
property.SetValue(entity, id);
_dbContext.Entry(entity).State = EntityState.Deleted;
}
else
{
var entity = _dbSet.Find(id);
if (entity != null) Delete(entity);
}
}
public void Delete(params T[] entities)
{
_dbSet.RemoveRange(entities);
}
public void Delete(IEnumerable<T> entities)
{
_dbSet.RemoveRange(entities);
}
[Obsolete("Method is replaced by GetList")]
public IEnumerable<T> Get()
{
return _dbSet.AsEnumerable();
}
[Obsolete("Method is replaced by GetList")]
public IEnumerable<T> Get(Expression<Func<T, bool>> predicate)
{
return _dbSet.Where(predicate).AsEnumerable();
}
public void Update(T entity)
{
_dbSet.Update(entity);
}
public void Update(params T[] entities)
{
_dbSet.UpdateRange(entities);
}
public void Update(IEnumerable<T> entities)
{
_dbSet.UpdateRange(entities);
}
public void Dispose()
{
_dbContext?.Dispose();
}
}
}