本文介绍了有没有办法通过反射或任何方式获取实体id字段的名称?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
User user = new User(); // User is a Entity
string idField = ????? //user.UserId
解决方案
如果您可以获取实体的EntitySet或EntityType,那么可以使用KeyMembers属性:
public IEnumerable< string> GetIdProperties(EntitySetBase entitySet)
{
返回GetIdProperties(entitySet.ElementType);
}
public IEnumerable< string> GetIdProperties(EntityTypeBase entityType)
{
在entityType.KeyMembers中从keyMember返回
select keyMember.Name
}
您可以从上下文获取一个通用对象集:
public ObjectSet< ; TEntity> GetEntitySet< TEntity>(ObjectContext context)
{
return context.CreateObjectSet< TEntity>();
}
I am trying to get the ID field name (property name) of an entity, is it possible?
User user= new User(); //User is an Entity
string idField = ??????? //user.UserId
解决方案
If you can get the EntitySet, or the EntityType, for the entity, then you can use the KeyMembers property:
public IEnumerable<string> GetIdProperties(EntitySetBase entitySet)
{
return GetIdProperties(entitySet.ElementType);
}
public IEnumerable<string> GetIdProperties(EntityTypeBase entityType)
{
return from keyMember in entityType.KeyMembers
select keyMember.Name
}
You can obtain a generic object set from the context:
public ObjectSet<TEntity> GetEntitySet<TEntity>(ObjectContext context)
{
return context.CreateObjectSet<TEntity>();
}
这篇关于有没有办法通过反射或任何方式获取实体id字段的名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!