2012-07-10 117 views
2

我想獲得實體中的表中的所有外鍵列。 例如:Linq to Sql如何獲取實體的所有外鍵字段

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

結果應該是這樣的:

  • ColumnWithForeignKey1Id
  • ColumnWithForeignKey2Id
  • ColumnWithForeignKey3Id

回答

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(); 
} 
1

在XML編輯器中打開的dbml文件,你會看到外鍵:

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

打開designer.cs文件,你會看到爲具有由或一個EntityRefEntitySet支持的System.Data.Linq.Mapping.AssociationAttribute屬性來實現外鍵。

如果您使用反射,請查找AssociationAttribute


如果您沒有使用設計器生成的模型類,裝飾用自己的屬性,這些屬性,所以你可以找到他們。

+0

我其實不知道如何收集外鍵,即使他們有這個屬性,我的意思是從後面的代碼。謝謝 – 2012-07-10 20:56:35

+0

下面是一個簡單反射示例的鏈接:http://msdn.microsoft.com/en-us/library/a4a92379.aspx – 2012-07-10 23:07:51

+0

是的,這是答案。我會在這裏發表一個例子,我希望你可以用這個例子更新答案;謝謝。 – 2012-08-07 09:24:52