如何通过检索表对象属性获取父表和子表以及表主键?

时间:2014-06-20 03:08:47

标签: asp.net linq linq-to-sql linq-to-entities linqpad

我的代码如下(credit:sgmoore)。它用于提取表的Parents表和Children表。

void Main()
{
    PropertyInfo[] props = typeof(Product).GetProperties();

    var parents = (from r in props
                  where r.PropertyType.GenericTypeArguments.Count() == 0
                  select r.Name)
                  .ToList().Dump("Parents Tables");

    var children = (from r in props
                   where r.PropertyType.GenericTypeArguments.Count() == 1
                   select r.Name)
                   .ToList().Dump("Children Tables");
}

结果是:

家长表:

类别, 供应商

儿童表:

订单明细, 车, 的评价

enter image description here

谢谢Sgmoore提供上面的代码。现在我想使输出像父/子表名加表主键。谁能提供解决方案将非常感激。

1 个答案:

答案 0 :(得分:1)

以下例程应该为您提供DataContext中任何表的主键

public static string GetPrimaryKey(DataContext dc , string tableName)
{        
    var table =  (from t in dc.Mapping.GetTables() where t.TableName == tableName || t.TableName == "[" + tableName + "]" select t).Single();

    return (from r in table.RowType.DataMembers where r.IsPrimaryKey select r.Name).Single();
}

所以你可以像

一样使用它
PropertyInfo[] props = typeof(Bank).GetProperties();

var parents = (from r in props 
               where r.PropertyType.GenericTypeArguments.Count() == 0 
               let TableName = r.PropertyType.Name
               select new { Column = r.Name  , TableName  , PrimaryKey = GetPrimaryKey(this, TableName) } )
               .ToList().Dump();

var children = (from r in props 
                where r.PropertyType.GenericTypeArguments.Count() == 1 
                let TableName = r.PropertyType.GenericTypeArguments.Single().Name
                select new { Column = r.Name  , TableName  , PrimaryKey = GetPrimaryKey(this , TableName) } )
               .ToList().Dump();

不确定这是否是最佳方式,但它应该有效。

相关问题