Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/asp.net/30.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Asp.net 如何通过检索表对象属性来获取父表和子表以及表主键?_Asp.net_Linq_Linq To Sql_Linq To Entities_Linqpad - Fatal编程技术网

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

Asp.net 如何通过检索表对象属性来获取父表和子表以及表主键?,asp.net,linq,linq-to-sql,linq-to-entities,linqpad,Asp.net,Linq,Linq To Sql,Linq To Entities,Linqpad,我有下面的代码(信用证:sgmoore)。它用于提取表的父表和子表 void Main() { PropertyInfo[] props = typeof(Product).GetProperties(); var parents = (from r in props where r.PropertyType.GenericTypeArguments.Count() == 0 select r.Name)

我有下面的代码(信用证:sgmoore)。它用于提取表的父表和子表

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");
}
结果是:

父表:

类别, 供应商

儿童表:

订单详情, 手推车, 评论


感谢Sgmoore提供上述代码。现在我想让输出像父/子表名加上表主键一样。能够提供解决方案的人将不胜感激。

以下例程将为您的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();

不确定这是否是最好的方法,但它应该会起作用。

非常感谢您,斯格摩尔!我感谢你的努力!