2012-02-15 81 views
0

我有以下代碼:我該如何執行這個簡單的相等比較?

public abstract class RepositoryBase<T, TId> : IRepository<T, TId> 
    where T : class, IEntityWithTypedId<TId> 
    where TId : IEquatable<TId>, IComparable<TId> 
{ 
    public T FindById(TId id) 
    { 
     T entity; 

     using (this.Context) // This simply returns the NHibernate Session 
     { 
      var entities = from e in this.Context.Get() 
          // where e.Id.Equals(id) 
          where e.Id == id 
          select e; 

      entity = entities.FirstOrDefault(); 
     } 

     return entity; 
    } 
} 

如果我使用where e.Id == id條款,我得到的錯誤:

error CS0019: Operator '==' cannot be applied to operands of type 'TId' and 'TId'

錯誤即使我已經告訴TId必須實現編譯IEquatableIComparable

如果我使用where e.Id.Equals(id)子句,代碼將會編譯,但是當它執行查詢時,NHibernate會收到一個NotSupported Exception FirstOrDefault一行。

我知道我必須在設計中遺漏一些東西,但是這個解決方案已經讓我失望了好幾天。

+3

爲什麼你不完全避免這個問題,並使用session.Get (id)? – Iain 2012-02-15 04:28:57

+0

你應該比較他們的密鑰,而不是實體本身... – 2012-02-15 04:37:20

+0

使用獲取(id)將是這個問題的最簡單的解決方案...;) – 2012-02-15 14:43:20

回答

1

雖然它看起來直觀,操作符(==<>等)有沒有關係一樣IComparableIEquatable接口等不幸的是,運營商不能應用於泛型類型。

Equals等函數不同,運算符是靜態的,因此不是多態。由於無法訪問泛型類型的靜態成員,操作符無法訪問。