首先使用Entity Framework 5,数据库。
是否可以(在运行时)获取实体属性所代表的数据库列的数据类型?如果更容易,.net类型也可以正常工作。
IEnumerable<DbEntityEntry> entities =
context.ChangeTracker.Entries()
.Where(
e =>
e.State == EntityState.Added || e.State == EntityState.Modified);
foreach (DbEntityEntry entity in entities)
{
foreach (string propertyName in entity.CurrentValues.PropertyNames)
{
//so I know the entity and the property name. Can I get the data type?
}
}
答案 0 :(得分:2)
在实体上使用反射来获取属性信息。
foreach (DbEntityEntry entity in entities)
{
foreach (string propertyName in entity.CurrentValues.PropertyNames)
{
var propertyInfo = entity.Entity.GetType().GetProperty(propertyName);
var propertyType = propertyInfo.PropertyType;
}
}
答案 1 :(得分:2)
获取表格特定列的数据类型:
[假设:实体道具类名称:供应商和列名称=&#34; VendorID&#34;]
string columnTypName = (context.Vendors.EntitySet.ElementType.Members["VendorID"].TypeUsage.EdmType).Name;
动态获取列的所有列名称和类型:
[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
};