我有一个例程来获取给定<T>
实体的主键名称。但是我不知道使用该值检索记录的语法。
对于给定的例程,例如:
public virtual T GetRecord(int id)
{
string keyName = GetKey(T);
// -------------- this is the part I don't know ---------------
//
return context.Entity<T>.Find(x => x.KeyName.Value == id);
//
//-------------------------------------------------------------
}
public virtual string GetKey(T entity)
{
var entityType = context.Model.FindEntityType(typeof(T));
var primaryKeyName = entityType.FindPrimaryKey().Properties.First().Name;
var set = context.Set<T>();
var orderedEntities = (set.OrderBy(e => e.GetType().GetProperty(primaryKeyName).GetValue(e, null))).ToList();
string keyName = context.Model
.FindEntityType(typeof(T))
.FindPrimaryKey()
.Properties
.Select(x => x.Name)
.Single();
return keyName;
}
您不需要密钥名称。EF已经知道将哪个属性用作主键,因此这应该可以工作:
context.Entry<T>.Find(id)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句