Reputation: 4496
I'm writing a simple logging mechanism for my app.
I have generic repository:
public class GenericRepository<TEntity>:IRepository<TEntity> where TEntity : class
{
internal Equipment_TestEntities context;
internal DbSet<TEntity> dbSet;
internal Log entry;
public GenericRepository(Equipment_TestEntities context)
{
this.context = context;
this.dbSet = context.Set<TEntity>();
this entry= new Log();
}
public virtual void Insert(TEntity entity)
{
dbSet.Add(entity);
AddLog("insert "+typeof(TEntity)+" "+entity.ToString());
}
private void AddLog(string action)
{
entry.Action = action;
entry.Date = DateTime.Now;
string username = HttpContext.Current.User.Identity.Name;
username = username.Substring(username.LastIndexOf("\\") + 1);
entry.Who = 1;
context.Logs.Add(entry);
}
}
In entry.Action
I want to keep:
In 1) I can easily hardcone action
2) I can use TypeOf
and get entity class name
But in 3rd I have a bit problem. In case of insert I can ask db for the newest record but what should I do in Edit/remove cases? Is there any ways to get properties value from those entities?
@Update:
sample part from unitOfWork:
public IRepository<Storage> storageRepository
{
get
{
if (this.StorageRepository == null)
{
this.StorageRepository = new GenericRepository<Storage>(context);
}
return StorageRepository;
}
}
IUnitOfWork: public interface IUnitOfWork : IDisposable { IRepository storageRepository { get; } }
Upvotes: 0
Views: 704
Reputation: 15053
I'd create an interface for the entities:
public interface IEntity
{
int? Id { get; set; }
}
Then change the generic constraint:
public class GenericRepository<TEntity>:IRepository<TEntity>
where TEntity : class, IEntity
{
...
}
Now you can simply use entity.Id to identify your entities.:
public virtual void Remove(TEntity entity)
{
if (!entity.Id.HasValue) {
throw new Exception("Cannot remove " + entity + ", it has no ID");
}
...
}
Upvotes: 1