读取通用存储库中的实体属性

时间:2014-05-07 07:48:21

标签: c# entity-framework

我正在为我的应用编写一个简单的日志记录机制。

我有通用存储库:

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

我希望保留entry.Action

  1. 行动例如。插入
  2. 使用哪个实体,例如。用户或角色
  3. 识别实体的东西
  4. 1)我可以很容易地采取行动 2)我可以使用TypeOf并获取实体类名称

    但是在第3节我有点问题。 在插入的情况下,我可以向db请求最新记录,但在编辑/删除案例中应该怎么办? 有没有办法从这些实体中获取属性值?

    @Update:

    来自unitOfWork的样本部分:

    public IRepository<Storage> storageRepository
        {
            get
            {
                if (this.StorageRepository == null)
                {
                    this.StorageRepository = new GenericRepository<Storage>(context);
                }
                return StorageRepository;
            }
        }
    

    IUnitOfWork: 公共接口IUnitOfWork:IDisposable     {          IRepository storageRepository {get; }     }

1 个答案:

答案 0 :(得分:1)

我将为实体创建一个界面:

public interface IEntity
{
    int? Id { get; set; }
}

然后更改通用约束:

public class GenericRepository<TEntity>:IRepository<TEntity> 
    where TEntity : class, IEntity
{
    ...
}

现在您可以简单地使用entity.Id来识别您的实体。:

public virtual void Remove(TEntity entity)
{
    if (!entity.Id.HasValue) {
        throw new Exception("Cannot remove " + entity + ", it has no ID");
    }
    ...
}
相关问题