I wish to get a list of columns names, types and whether the column is a PK of a table object in Entity Framework.
How do I do this in C# (4.0) (ideally generically)?
The winning answer will be one that does it efficiently and most importantly generically.
In Entity Framework Core we can select specific columns by using either anonymous types or DTOs.
var names = typeof(User). GetProperties() . Select(property => property.Name) . ToArray();
You could use the LINQ select clause and reference the property that relates to your Name column. Show activity on this post. If you're fetching a single item only then, you need use select before your FirstOrDefault()/SingleOrDefault(). And you can use anonymous object of the required properties.
if you want only column names then ,i got the best answer :var properties = (from t in typeof(YourTableName).GetProperties()
select t.Name).ToList();
var name= properties[0];
Got it - I used a linq based reflection query:
IEnumerable<FieldList> properties = from p in typeof(T).GetProperties()
where (from a in p.GetCustomAttributes(false)
where a is EdmScalarPropertyAttribute
select true).FirstOrDefault()
Sorted! Thanks for the suggestions all.
FYI - I am creating a dynamic where clause using LINQ, dynamic lambda expressions to build e.g. search which will automatically search through all columns by default. But I also needed the column names to verify because I will allow this to be overridden and these calls will be done via javascript ajax post whose input cannot be trusted - so needed to verify the column names.
I used the above to place the results into a custom object with properties called FieldName, FieldType, PrimaryKey. Ta daaa.
Customise it further with
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,
FieldPK = p.GetCustomAttributes(false).Where(a => a is EdmScalarPropertyAttribute && ((EdmScalarPropertyAttribute)a).EntityKeyProperty).Count() > 0
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With