我想制作基本统计数据来获取表格或实体的数据计数,我想问我是否可以在实体框架中的一个查询中执行此操作?我可以在SQL查询中通过在存储过程中创建多于select语句来实现这一点
答案 0 :(得分:0)
这是我的方法,最后你仍然应该构建SQL Select语句,但仍然。
首先,您应该添加名称空间:
using System.Data.Entity.Core.Metadata.Edm;
using System.Data.Entity.Infrastructure;
using System.Data.Entity.Core.Objects;
然后您可以使用此代码获取所有带行数的表。
YourDBEntities ent = new YourDBEntities();
ObjectContext context = ((IObjectContextAdapter)ent).ObjectContext;
MetadataWorkspace metadataWorkspace = context.MetadataWorkspace;
EntityContainer container = metadataWorkspace
.GetItems<EntityContainer>(DataSpace.CSpace).First();
ReadOnlyMetadataCollection<EntitySetBase> entitySetBase = container.BaseEntitySets;
//Get Table Names
var tableNames = entitySetBase
.Where(x => x.BuiltInTypeKind == BuiltInTypeKind.EntitySet) //Get Tables Only
.Select(x => x.Name);
//Get data
foreach (var tableName in tableNames)
{
//Counstruct query for each table
var selectSQL = String.Format(@"SELECT '{1}', COUNT(1) AS Count
FROM {0}", tableName, tableName);
ObjectQuery<DbDataRecord> query = context.CreateQuery<DbDataRecord>(selectSQL);
ObjectResult<DbDataRecord> results = query.Execute(MergeOption.AppendOnly);
DbDataRecord res = results.First();
//Write to console
Console.WriteLine("Table '{0}' contains {1} of rows", res[0], res[1]);
}