Get Column DataType from Entity Framework Entity

后端 未结 2 1012
感情败类
感情败类 2021-01-14 17:38

Using Entity Framework 5, database first.

Is it possible (at run time) to get the data type of the database column that an entity\'s property represents? The .net t

2条回答
  •  不要未来只要你来
    2021-01-14 18:12

    To get the data type of the particular column of the table:

    [Assume: Entity prop class name: Vendors and column name ="VendorID"]

    string columnTypName =   (context.Vendors.EntitySet.ElementType.Members["VendorID"].TypeUsage.EdmType).Name;
    

    To get all columns names and type of the columns dynamically:

    [Param : tableName]

    var columns = 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 == tableName)
                           select new
                           {
                               colName = p.Name,
                               colType = p.TypeUsage.EdmType.Name
                           };
    

提交回复
热议问题