在Linq to Sql中如何获取一个实体的所有外键字段 [英] In Linq to Sql How to get all the foreign key fields for an entity
问题描述
我想在我的实体中获取表中的所有外键列。
例如:
class User
{
Id {get; set;}
$ b $ ColumnWithForeignKey2Id {get; set;}
ColumnWithForeignKey3Id {get; set;}
$ b $ $ b
结果应该是这样: 感谢 I'd like to get all the Foreign Key columns in a Table in my entity.
For example: result should be like:
下面是一个例子,收集定义了一个特殊属性的ForeignKeys;对于这个问题AssociationAttribute和给定的类内部,这个例子ClassName。
David B
的指导。
public void Get< TAttribute>(object obj,bool inherit)其中TAttribute:System.Attribute
$ b 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();
}
class User
{
Id {get;set;}
Name {get;set;}
ColumnWithForeignKey1Id{get;set;}
ColumnWithForeignKey2Id{get;set;}
ColumnWithForeignKey3Id{get;set;}
}
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();
}
这篇关于在Linq to Sql中如何获取一个实体的所有外键字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!