我正在爲我的應用程序寫一個簡單的日誌記錄機制。閱讀普通存儲庫中的實體屬性
我有通用倉庫:
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)我可以很容易地hardcone行動 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 {得到; }}
爲什麼不爲你的實體創建一個接口('TEntity:IEntity')然後定義一個Id本身ty在那個界面中? – sroes
如果不是Db中的所有實體/表都有Id/PrimaryKey,它應該如何顯示? – szpic
你的代碼有臭味......我的意思是你沒有正確地使用依賴注入,而btw私有字段應該(但不是必須)以下劃線開始 - 這是一個命名約定,並且在構造函數中儘量避免編寫「this」。你應該寫一些'_context = context;'並且抱歉我不知道你的問題的答案。 – rosko