2

エンティティのテーブルにあるすべての外部キー列を取得したいのですが。例えば:

class User
{
    Id {get;set;}
    Name {get;set;}
    ColumnWithForeignKey1Id{get;set;}
    ColumnWithForeignKey2Id{get;set;}        
    ColumnWithForeignKey3Id{get;set;}
}

結果は次のようになります。

  • ColumnWithForeignKey1Id
  • ColumnWithForeignKey2Id
  • ColumnWithForeignKey3Id
4

2 に答える 2

1

xmlエディターでdbmlファイルを開くと、外部キーが表示されます。

  <Association Name="Table1_Table2" Member="Table1" ThisKey="Table2ID" OtherKey="ID" Type="Table2" IsForeignKey="true" />

Designer.csファイルを開くと、またはのいずれかで裏付けられたaを持つプロパティとして実装された外部キーが表示されSystem.Data.Linq.Mapping.AssociationAttributeます。EntityRefEntitySet

リフレクションを使用している場合は、を探してくださいAssociationAttribute


デザイナを使用してモデリングクラスを生成していない場合は、それらのプロパティを独自の属性で装飾して、見つけられるようにします。

于 2012-07-10T20:26:49.890 に答える
0

特別な属性で定義されたForeignKeysを収集する例を次に示します。この質問「AssociationAttribute」および特定のクラス内、この例では「ClassName」。

David B指導ありがとうございます。

public void Get<TAttribute>(object obj, bool inherit) where TAttribute : System.Attribute
{
     var ForeignKeyCollection = typeof(ClassName).GetProperties(BindingFlags.Instance | BindingFlags.Public)
                .Where(p => p.GetCustomAttributes(typeof(TAttribute), true).Any())
                .Select(p => new
                                 {
                                     Property = p,
                                     Attribute = (AssociationAttribute)Attribute.GetCustomAttribute(p, typeof(TAttribute), true)
                                 })
                .Where(p => p.Attribute.IsForeignKey).ToList();
}
于 2012-08-07T15:06:17.353 に答える