实体框架 - 如何获取列? [英] Entity Framework - how do I get the columns?
问题描述
我希望获得列名称、类型以及该列是否是实体框架中表对象的 PK 的列表.
I wish to get a list of columns names, types and whether the column is a PK of a table object in Entity Framework.
我如何在 C# (4.0) 中执行此操作(理想情况下是通用的)?
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.
推荐答案
明白了 - 我使用了基于 linq 的反射查询:
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.
仅供参考 - 我正在使用 LINQ 创建一个动态 where 子句,动态 lambda 表达式来构建例如search 默认情况下会自动搜索所有列.但我还需要验证列名,因为我将允许覆盖它,并且这些调用将通过 javascript ajax post 完成,其输入不可信 - 因此需要验证列名.
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.
我使用上面的方法将结果放入一个自定义对象中,该对象具有名为 FieldName、FieldType、PrimaryKey 的属性.呸.
I used the above to place the results into a custom object with properties called FieldName, FieldType, PrimaryKey. Ta daaa.
使用
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
};
这篇关于实体框架 - 如何获取列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!