2014-05-07 19 views
0

我正在爲我的應用程序寫一個簡單的日誌記錄機制。閱讀普通存儲庫中的實體屬性

我有通用倉庫:

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)我可以很容易地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 {得到; }}

+0

爲什麼不爲你的實體創建一個接口('TEntity:IEntity')然後定義一個Id本身ty在那個界面中? – sroes

+0

如果不是Db中的所有實體/表都有Id/PrimaryKey,它應該如何顯示? – szpic

+0

你的代碼有臭味......我的意思是你沒有正確地使用依賴注入,而btw私有字段應該(但不是必須)以下劃線開始 - 這是一個命名約定,並且在構造函數中儘量避免編寫「this」。你應該寫一些'_context = context;'並且抱歉我不知道你的問題的答案。 – rosko

回答

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

但是這會拋出:'Error 'TEntity'類型必須是參考類型才能用作通用類型或方法'System.Data.Entity.DbSet '\t ' – szpic

+0

'參數'TEntity'我的不好,請參閱我的編輯 – sroes

+0

現在這破壞了我的unitOfWork:'錯誤類型'magazyn.Models.User'不能用作泛型類型或方法'magazyn.DAL.GenericRepository '中的類型參數'TEntity'。沒有從'magazyn.Models.User'到'magazyn.DAL.IEntity'的隱式引用轉換。 \t ' – szpic