在LINQPad中,我正在尝试打印数据库中的所有表并在每个表中计算行数:
this.Mapping.GetTables().Select(o => new { TableName = o.TableName, RowCount = ? })
如何计算行数?
答案 0 :(得分:3)
我需要做同样的事情,而我只查看包含数据的表格。我很快发现你必须小心你从这里撤回的东西,因为数据是深度嵌套的。下面的查询在我的机器上运行不到一秒钟,我在数据库中有大约266个表(不包括视图)。 我希望这能回答你的问题。
var list = this.Mapping.GetTables()
.Select(o => new {
TableName = o.TableName,
Type_ = o.RowType.Type,
IsEntity = o.RowType.IsEntity,
RowCount = this.GetTable(o.RowType.Type).Cast<object>().Count(),
})
.Where (o => o.IsEntity && o.RowCount > 0)
.ToList();
list.Dump();
答案 1 :(得分:2)
this.Mapping.GetTables().Select(o => new {
TableName = o.TableName,
RowCount = (
(IEnumerable<object>)this.GetType().GetProperty(
o.TableName.Substring(1, o.TableName.Length-2)
).GetValue(this, null))
.Count()
}).Dump();
向this answer from Jason致敬,了解如何按名称查找表格。
答案 2 :(得分:1)
试试这个:
var list = this.Mapping.GetTables()
.Select(o => new { TableName = o.TableName, Type_ = o.Row.Type, RowCount = 0 }).ToList();
list.ForEach(x=>x.RowCount = this.GetTable(x.Type_).Count);
list.Select(o=> new { TableName = o.TableName, RowCount = 0 });
答案 3 :(得分:0)
var list = from o in this.Mapping.GetTables()
let rowCount = ExecuteQuery<int>("select count(*) from "+ o.TableName).FirstOrDefault()
select new {
TableName = o.TableName,
RowCount = rowCount
};
答案 4 :(得分:0)
或者不使用Mapping:
this.GetType().GetProperties().Where(p => p.DeclaringType == typeof(TypedDataContext)).Select(t => new
{
TableName = t.Name,
RowCount = ((IEnumerable<object>)(this.GetType().GetProperty(t.Name).GetValue(this, null))).Count()
}).Dump();
答案 5 :(得分:-4)
这不是LinqPad问题,而是Linq问题。但是,让我给你一个很好的LinqPad提示。将.Dump()添加到您的查询中,看看你得到了什么 - 非常酷。
this.Mapping.GetTables().Select(o => new { TableName = o.TableName, RowCount = ? }).Dump()