在Linq to Sql中如何获取一个实体的所有外键字段 [英] In Linq to Sql How to get all the foreign key fields for an entity

查看:137
本文介绍了在Linq to Sql中如何获取一个实体的所有外键字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在我的实体中获取表中的所有外键列。
例如:

  class User 
{
Id {get; set;}
$ b $ ColumnWithForeignKey2Id {get; set;}
ColumnWithForeignKey3Id {get; set;}
$ b $ $ b

结果应该是这样:


  • ColumnWithForeignKey1Id

  • ColumnWithForeignKey2Id
  • ColumnWithForeignKey3Id
    下面是一个例子,收集定义了一个特殊属性的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();
    }


    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

    解决方案

    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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆