2010-11-23 18 views
0

Entity Frameworkバージョン1を使用していますが、汎用リポジトリを作成しようとしていますが、各テーブルの主キーを取得する方法が見つかりません。誰かがこの問題を解決しましたか?Entity Framework:汎用リポジトリとテーブルの主キー

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

+0

@残念 - このSOの答えをチェックアウト:http://stackoverflow.com/questions/2958921/entity-framework-4-how-to-find-the-primary-key/3046102#3046102 EF1で作業します。 – RPM1984

+0

が役に立ちます。あなたが私に送ったリンクは、DataContextを持っているのに対し、OjbectContextを使っていることに気付きました。 VSにソリューションを移植する際のヒントは、DataContextを使用するモデルを生成しましたか? – Remus

関連する問題