我可以创建一个动态查询,但现在需要输入列。我宁愿允许从组合框中进行选择。
我可以用这个
获取表格using (var dbContext = new SalesEntities())
{
var metadata = ((IObjectContextAdapter)dbContext).ObjectContext.MetadataWorkspace;
var tables = metadata.GetItemCollection(DataSpace.SSpace)
.GetItems<EntityContainer>()
.Single()
.BaseEntitySets;
foreach (var table in tables)
{
cboTable.Items.Add(table.Name );
}
}
我最终用这个运行查询(如果有一种方法可以推广这个代码,那么就不会为每个表进行复制)
List<Sales_Regions> srsl;
var query1 = SC.Sales_Regions.Where(txtField.Text + " = @0", txtValue.Text);
srsl = query1.ToList();
dataGridView1.DataSource = srsl;
查看这篇文章(Entity Framework - how do I get the columns?)我试过这个:
IEnumerable<FieldList> properties = from p in typeof(T).GetProperties()
where (from a in p.GetCustomAttributes(false)
where a is EdmScalarPropertyAttribute
select true).FirstOrDefault()
select new FieldList
{
FieldName = p.Name,
FieldType = p.PropertyType.ToString (),
FieldPK = p.GetCustomAttributes(false).Where(a => a is EdmScalarPropertyAttribute && ((EdmScalarPropertyAttribute)a).EntityKeyProperty).Count() > 0
};
我创建了一个课程(不知道这是不是错了)
class FieldList
{
public string FieldName
{
get;
set;
}
public string FieldType
{
get;
set;
}
public bool FieldPK
{
get;
set;
}
}
但是我收到了错误
类型或命名空间名称&#39; T&#39;找不到(你错过了使用指令或汇编引用吗?)
我尝试过几件事,但事实是我不知道那是什么。
这个可能实际上更好,我让代码工作,但我不知道如何从cols中获取数据。
var cols = from meta in objctx.MetadataWorkspace.GetItems(DataSpace.CSpace)
.Where(m => m.BuiltInTypeKind == BuiltInTypeKind.EntityType)
from p in (meta as EntityType).Properties
.Where(p => p.DeclaringType.Name == cboTable.SelectedItem.ToString())
select new
{
PropertyName = p.Name,
TypeUsageName = p.TypeUsage.EdmType.Name, //type name
Documentation = p.Documentation != null ? p.Documentation.LongDescription : null //if primary key
};
看起来我真的很亲近。尽量保持活力。