反射または何によってエンティティID:フィールドの名前を取得する方法はありますか?
-
21-08-2019 - |
質問
私はそれが可能であり、エンティティのIDフィールド名(プロパティ名)を取得しようとしています!
ユーザのユーザ=新しいユーザー(); //ユーザーがエンティティである
文字列idField = ??????? //user.UserId
解決
あなたはのEntitySet、またはEntityTypeを得ることができる場合は、エンティティのために、そしてあなたがKeyMembersプロパティを使用することができます:
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
}
あなたは文脈から設定、一般的なオブジェクトを取得することができます:
public ObjectSet<TEntity> GetEntitySet<TEntity>(ObjectContext context)
{
return context.CreateObjectSet<TEntity>();
}
他のヒント
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;
}
あなたは一つに両方のfuncsをマージしたり、検索条件を設定することができます。
このポストEntity Frameworkのサポートフォーラムでには、IDフィールドとその詳細を見つけるためにリフレクションを使用する方法を示します。
Entityクラスは、私は反射がまだそれに取り組むだろうと思い、まだSystem.Data.Objects.DataClasses.EntityObjectから継承するクラスで、そう。
あなたはそれを試してみましたか?あなたが任意のエラーを取得するのですか?
所属していません StackOverflow