I can create a dynamic query but as it stands now the column needs to be typed in. I would prefer to allow selection from a combobox.
I can get the tables with this
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 );
}
}
And I eventually run the query with this (It would be nice if there was a way I can generalize this code so it is not reproduced for each table)
List<Sales_Regions> srsl;
var query1 = SC.Sales_Regions.Where(txtField.Text + " = @0", txtValue.Text);
srsl = query1.ToList();
dataGridView1.DataSource = srsl;
Looking at this post (Entity Framework - how do I get the columns?) I tried this:
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
};
And I created a class to go with it (don't know if this is wrong or not)
class FieldList
{
public string FieldName
{
get;
set;
}
public string FieldType
{
get;
set;
}
public bool FieldPK
{
get;
set;
}
}
But I get an error
The type or namespace name 'T' could not be found (are you missing a using directive or an assembly reference?)
I tried several things but the fact of the matter is I do not know what goes there.
This one may actually be better, I got the code to work, but I don't know how to get the data out of 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
};
It seems like I'm really close. Trying to be as dynamic as possible.