Entity framework 4 EF4按ID的通用搜索
我有x个表,所有表都有一个uniqueidentifier/guid主键。我想写一个通用函数,它将采用Guid参数id,其中T是EntityObject,如下所示Entity framework 4 EF4按ID的通用搜索,entity-framework-4,Entity Framework 4,我有x个表,所有表都有一个uniqueidentifier/guid主键。我想写一个通用函数,它将采用Guid参数id,其中T是EntityObject,如下所示 public T SelectById<T>(Guid id) where T : EntityObject public T SelectById(Guid id),其中T:EntityObject 这似乎是一件简单的事情。我在互联网上搜索过,但找不到一个很好的方法,更不用说优雅的方法了。我在这里遗漏了什么,为什么这
public T SelectById<T>(Guid id) where T : EntityObject
public T SelectById(Guid id),其中T:EntityObject
这似乎是一件简单的事情。我在互联网上搜索过,但找不到一个很好的方法,更不用说优雅的方法了。我在这里遗漏了什么,为什么这么困难?为了实现这一点,您需要确保实体上的ID属性符合命名约定,比如ID或EntityName\u ID。然后,您所要做的就是使用一点反射来构建EntityKey
ObjectStateEntry entry;
var entityKey = new EntityKey(Context.DefaultContainerName + "." + typeof(T).Name, "Id", id);
object entity = null;
if (!Context.ObjectStateManager.TryGetObjectStateEntry(entityKey, out entry) || entry.Entity == null)
{
try
{
entity = Context.GetObjectByKey(entityKey);
}
catch (ObjectNotFoundException)
{
}
}
return (T)entity;