I have a DB that all of its entities have some log fields for Create/Modify/Delete and I have to take Current User Id in all of my CRUD Actions and set these fields for secu
Alright so you have to make a clear IRepository and make it as simple as possible like this(since you want this Generic):
IRepository:
public interface IRepository<T>
{
void Add(T entity);
void Delete(T entity);
void Delete(int id);
T GetById(int id);
IEnumerable<T> GetAll();
void Update(T entity);
void save();
}
And Create One Generic Repository like below:
public class Repository<T> : IRepository<T>
where T : EntityBase
{
internal MyDbContext context;
internal DbSet<T> dbSet;
public Repository()
{
context = new MyDbContext();
this.dbSet = context.Set<T>();
}
public void Add(T entity)
{
dbSet.Add(entity);
}
public void Delete(T entity)
{
dbSet.Remove(entity);
}
public void Delete(int id)
{
dbSet.Remove(dbSet.Find(id));
}
public T GetById(int id)
{
return dbSet.Find(id);
}
public IEnumerable<T> GetAll()
{
return dbSet.AsEnumerable();
}
public void Update(T entity)
{
dbSet.Attach(entity);
context.Entry(entity).State = EntityState.Modified;
}
public void save()
{
context.SaveChanges();
}
}
Good thing about EntityBase is since all of your properties have an id, you can easily go like this:
public class EntityBase
{
public int id { get; set; }
}
And then implement this to your Models :
public class Example : EntityBase
{
public byte RecordStatus { get; set; }
public string RecordStatusDescription { get; set; }
public string CreatedBy { get; set; }
public DateTime CreatedDateTime { get; set; }
public string CreatorIPAddress { get; set; }
public string ModifiedBy { get; set; }
public DateTime ModifiedDateTime { get; set; }
public string ModifierIPAddress { get; set; }
public string RemovedBy { get; set; }
public string RemovedDateTime { get; set; }
public string RemoverIPAddress { get; set; }
public bool IsRemoved { get; set; }
}
Advantage of using this simple Repository is you can easily do anything with it e.g. :
public class HomeController : Controller
{
Repository<Example> _repository = new Repository<Example>();
public ActionResult Index()
{
vm.Example = _repository.GetAll()
.Where(x => x.RecordStatusDescription == "1").ToList();
return View("index",vm);
}
}