实体框架 - 如何获取列?

Dan*_*n B 18 c# generics entity-framework asp.net-mvc-3

我希望获得列名称,类型以及列是否是Entity Framework中表对象的PK的列表.

我如何在C#(4.0)(理想情况下)中执行此操作?

获胜的答案将是有效且最重要的是一般的答案.

Dan*_*n B 10

知道了 - 我使用了基于linq的反射查询:

IEnumerable<FieldList> properties = from p in typeof(T).GetProperties()
                                    where (from a in p.GetCustomAttributes(false)
                                    where a is EdmScalarPropertyAttribute   
                                    select true).FirstOrDefault()
Run Code Online (Sandbox Code Playgroud)

排序!谢谢你的建议.

仅供参考 - 我正在使用LINQ创建动态where子句,动态lambda表达式构建例如搜索,默认情况下将自动搜索所有列.但我还需要验证列名,因为我将允许覆盖它,并且这些调用将通过javascript ajax post完成,其输入不可信任 - 因此需要验证列名.

我使用上面的方法将结果放入一个名为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
                                     };    
Run Code Online (Sandbox Code Playgroud)

  • 任何不反思的方式? (2认同)

Ash*_*dar 7

如果你只想要列名,我得到了最好的答案:
var properties = (from t in typeof(YourTableName).GetProperties() select t.Name).ToList(); var name= properties[0];


Pet*_*_ch 5

如果您不想使用反射,请参阅此处的答案.将实体名称替换为您的实体名称

var cols = from meta in ctx.MetadataWorkspace.GetItems(DataSpace.CSpace)
                       .Where(m=> m.BuiltInTypeKind==BuiltInTypeKind.EntityType)
                    from p in (meta as EntityType).Properties
                       .Where(p => p.DeclaringType.Name == "EntityName")
                   select new
                      {
                       PropertyName = p.Name,
                       TypeUsageName = p.TypeUsage.EdmType.Name, //type name
                       Documentation = p.Documentation != null ?               
                                       p.Documentation.LongDescription : null //if primary key
        };
Run Code Online (Sandbox Code Playgroud)