簡體   English   中英

在通用存儲庫中讀取實體屬性

[英]Reading entity properties in 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);
    }
}

entry.Action我要保留:

  1. 動作例如 插入
  2. 使用哪個實體 用戶或角色
  3. 識別實體的東西

1)我可以輕松地采取行動2)我可以使用TypeOf並獲取實體類名稱

但是在第三屆我有一個問題。 如果要插入,我可以向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; }}

我將為實體創建一個接口:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM