Shi*_*mmy 1 .net c# reflection entity-framework propertyinfo
我想获取一个实体的ID字段名称(属性名称),是否可能?
用户user = new User(); //用户是一个实体
string idField = ??????? //user.UserId
public static IEnumerable<string> GetIdFields<TEntity>() where TEntity
: EntityObject
{
var ids = from p in typeof(TEntity).GetProperties()
where (from a in p.GetCustomAttributes(false)
where a is EdmScalarPropertyAttribute &&
((EdmScalarPropertyAttribute)a).EntityKeyProperty
select true).FirstOrDefault()
select p.Name;
return ids;
}
public static string GetIdField<TEntity>() where TEntity : EntityObject
{
IEnumerable<string> ids = GetIdFields<TEntity>();
string id = ids.Where(s => s.Trim().StartsWith(typeof(TEntity).Name.
Trim())).FirstOrDefault();
if (string.IsNullOrEmpty(id)) id = ids.First();
return id;
}
Run Code Online (Sandbox Code Playgroud)
您可以将两个func合并为一个或设置搜索条件.
| 归档时间: |
|
| 查看次数: |
7535 次 |
| 最近记录: |