2012-07-10 148 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