有没有办法使用 LINQ to SQL 从 table 中找出外键的列名?

Is there a way to find out the column name of a Foreign key from a table using LINQ to SQL?

假设我有两个 tables:

客户:ID(pk),客户名称

订单:ID(pk),Client_ID(fk),订单名称

我想找出订单中外键列的名称table。

我可以使用以下代码获取主键列的名称:

     public static string prkFieldName<T>(this DataContext context) where T:class
    {
        var table = context.GetTable<T>();
        var mapping = context.Mapping.GetTable(typeof(T));
        var prkfield = mapping.RowType.DataMembers.SingleOrDefault(d => d.IsPrimaryKey);
        if(prkfield==null)
        {
            return null;
        }

        return prkfield.Name;
    }

但是当我尝试获取外键列的名称时,我只能知道 'CLient' table 已被引用。但是我不知道列名是'Client_ID'。

最后,我应该可以得到作为外键的列的名称。有没有可能?谢谢

 public static string[] fkFieldName<T>(this DataContext context) where T : class
    {
        var table = context.GetTable<T>();
        var mapping = context.Mapping.GetTable(typeof(T));

        var fkfield = mapping.RowType.DataMembers.Where(d => d.Association!=null).Where(s=>s.Association.IsForeignKey);


        if (fkfield == null)
        {
            return null;
        }


        var fkFieldNames = skfield.Select(c => c.Name).ToArray();

        return fkFieldNames;
    }

我认为您需要返回属性或字段信息和属性,因此以下内容对我有用。

public static string[] fkFieldName<T>(this DataContext context ) where T : class
{
    var table = context.GetTable<T>();

    const BindingFlags bindingFlags = BindingFlags.Public | BindingFlags.Instance;
    MemberInfo[] members = typeof(T).GetFields(bindingFlags).Cast<MemberInfo>()
                   .Concat(typeof(T).GetProperties(bindingFlags)).ToArray();

    var mapping = context.Mapping.GetTable(typeof(T));

    var fkfield = mapping.RowType.DataMembers.Where(d => d.Association != null).Where(s => s.Association.IsForeignKey).ToList();

    string[] fkNames = new string[fkfield.Count()];

    for(int i= 0 ; i < fkfield.Count() ; i++)
    {
        var mi = members.Single(a=>a.Name == fkfield[i].Name) ;
        var attr = (System.Data.Linq.Mapping.AssociationAttribute)mi.GetCustomAttribute(typeof(System.Data.Linq.Mapping.AssociationAttribute));
        fkNames[i] = attr.ThisKey;
    }
    return fkNames;
}