简体   繁体   中英

Reading entity properties in generic repository

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:

  1. Action eg. Insert
  2. Which entityUsed eg. User or Role
  3. Something to identify entity

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; } }

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");
    }
    ...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM