从实体框架实体获取列数据类型
本文关键字:实体 数据类型 框架 获取 | 更新日期: 2023-09-27 18:32:12
使用实体框架 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?
}
}
使用实体上的反射来获取属性信息。
foreach (DbEntityEntry entity in entities)
{
foreach (string propertyName in entity.CurrentValues.PropertyNames)
{
var propertyInfo = entity.Entity.GetType().GetProperty(propertyName);
var propertyType = propertyInfo.PropertyType;
}
}
获取表中特定列的数据类型:
[假设:实体属性类名称:供应商和列名称 ="供应商 ID"]
string columnTypName = (context.Vendors.EntitySet.ElementType.Members["VendorID"].TypeUsage.EdmType).Name;
要动态获取列的所有列名和类型,请执行以下操作:
[参数:表名称]
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
};