2010-06-21 35 views
2

我有x個表和所有表都有一個uniqueidentifier/guid主鍵。我想編寫一個通用的功能,將採取一個GUID PARAM id其中T是EntityObject是這樣的...EF4通用搜索ID

public T SelectById<T>(Guid id) where T : EntityObject 

看起來這是一個簡單的事情。我搜索了互聯網,無法找到辦法做到這一點,更不用說是一種優雅的方式。我在這裏錯過了什麼,爲什麼這很困難?

回答

3

爲了實現這一點,您需要確保您的實體上的ID屬性符合命名約定,如Id或EntityName_Id。然後你所要做的就是使用一點反射來建立EntityKey。

  ObjectStateEntry entry; 

     var entityKey = new EntityKey(Context.DefaultContainerName + "." + typeof(T).Name, "Id", id); 

     object entity = null; 
     if (!Context.ObjectStateManager.TryGetObjectStateEntry(entityKey, out entry) || entry.Entity == null) 
     { 
      try 
      { 
       entity = Context.GetObjectByKey(entityKey);  
      } 
      catch (ObjectNotFoundException) 
      { 

      } 

     } 

     return (T)entity;