2010-11-23 57 views
0

我正在使用實體框架版本1,我試圖創建一個通用的存儲庫,但我找不到一種方法來獲取每個表的主鍵。有沒有人解決過這個問題?實體框架:通用存儲庫和表主鍵

UPDATE:我的目標使用了這將是一個通用的方法是這樣的:你必須使用某種反思

TModel GetByPrimaryKey(Guid key) 
{ 

} 

回答

3

最後,我適應@馬克的答案從這裏:C# Linq-SQL: An UpdateByID method for the Repository Pattern

的結果是這樣的:

public TModel GetByPrimaryKey(Guid key) 
    { 
     // get the row from the database using the meta-model 
     MetaType meta = _DB.Mapping.GetTable(typeof(TModel)).RowType; 
     if (meta.IdentityMembers.Count != 1) throw new InvalidOperationException("Composite identity not supported"); 
     string idName = meta.IdentityMembers[0].Member.Name; 

     var param = Expression.Parameter(typeof(TModel), "row"); 
     var lambda = Expression.Lambda<Func<TModel, bool>>(
      Expression.Equal(
       Expression.PropertyOrField(param, idName), 
       Expression.Constant(key, typeof(Guid))), param); 

     return _DB.GetTable<TModel>().FirstOrDefault(lambda); 
    } 

... _DB是DataContext

我希望這可以幫助未來的人。

0

嘗試這樣:

private PropertyInfo GetPrimaryKeyInfo<T>() 
{ 
    PropertyInfo[] properties = typeof(T).GetProperties(); 
    foreach (PropertyInfo pI in properties) 
    { 
     System.Object[] attributes = pI.GetCustomAttributes(true); 
     foreach (object attribute in attributes) 
     { 
      if (attribute is EdmScalarPropertyAttribute) 
      { 
       if ((attribute as EdmScalarPropertyAttribute).EntityKeyProperty == true) 
        return pI; 
      } 
      else if (attribute is ColumnAttribute) 
      { 

       if ((attribute as ColumnAttribute).IsPrimaryKey == true) 
        return pI; 
      } 
     } 
    } 
    return null; 
} 
+0

謝謝 - 我應該從頭開始更清楚。我的目標是在「getbyprimarykey」通用方法中使用這些信息。我已經更新了這個問題。 – Remus 2010-11-23 01:09:05