问题
I'd like to get all the Foreign Key columns in a Table in my entity. For example:
class User
{
Id {get;set;}
Name {get;set;}
ColumnWithForeignKey1Id{get;set;}
ColumnWithForeignKey2Id{get;set;}
ColumnWithForeignKey3Id{get;set;}
}
result should be like:
- ColumnWithForeignKey1Id
- ColumnWithForeignKey2Id
- ColumnWithForeignKey3Id
回答1:
Open your dbml file in an xml editor and you'll see foreign keys:
<Association Name="Table1_Table2" Member="Table1" ThisKey="Table2ID" OtherKey="ID" Type="Table2" IsForeignKey="true" />
Open the designer.cs file and you'll see foreign keys implemented as a property that has a System.Data.Linq.Mapping.AssociationAttribute which is backed by either an EntityRef or EntitySet.
If you're using reflection, look for AssociationAttribute.
If you aren't using the designer to generate the modeling classes, decorate those properties with your own attribute so you can find them.
回答2:
Here is a example, to gather the ForeignKeys defined with a special attribute; for this question "AssociationAttribute" and inside a given class, for this example "ClassName".
Thanks for David B for the guidance.
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();
}
来源:https://stackoverflow.com/questions/11421200/in-linq-to-sql-how-to-get-all-the-foreign-key-fields-for-an-entity