我有以下通用扩展方法:
public static T GetById<T>(this IQueryable<T> collection, Guid id) where T : IEntity { Expression<Func<T, bool>> predicate = e => e.Id == id; T entity; // Allow reporting more descriptive error messages. try { entity = collection.SingleOrDefault(predicate); } catch (Exception ex) { throw new InvalidOperationException(string.Format( "There was an error retrieving an {0} with id {1}. {2}", typeof(T).Name, id, ex.Message), ex); } if (entity == null) { throw new KeyNotFoundException(string.Format( "{0} with id {1} was not found.", typeof(T).Name, id)); } return entity; }
不幸的是,predicate由于C#将谓词转换为以下内容,因此Entity Framework不知道如何处理:
predicate
e => ((IEntity)e).Id == id
实体框架引发以下异常:
无法将类型“ IEntity”强制转换为类型“ SomeEntity”。LINQ to Entities仅支持强制转换EDM基本类型或枚举类型。
我们如何使实体框架与我们的IEntity界面一起工作?
IEntity
通过将class通用类型约束添加到扩展方法中,我能够解决此问题。不过,我不确定为什么会起作用。
class
public static T GetById<T>(this IQueryable<T> collection, Guid id) where T : class, IEntity { //... }