LINQ到实体仅支持铸造EDM基元或枚举类型与IEntity接口 [英] LINQ to Entities only supports casting EDM primitive or enumeration types with IEntity interface
问题描述
我有以下的通用扩展方法:
I have the following generic extension method:
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#转换的predicate以下内容:
Unfortunately Entity Framework doesn't know how to handle the predicate
since C# converted the predicate to the following:
e => ((IEntity)e).Id == id
实体框架抛出以下异常:
Entity Framework throws the following exception:
无法转换类型IEntity'输入'SomeEntity。 LINQ到 实体仅支持铸造EDM基元或枚举类型。
Unable to cast the type 'IEntity' to type 'SomeEntity'. LINQ to Entities only supports casting EDM primitive or enumeration types.
如何才能让我们的 IEntity
接口实体框架的工作?
How can we make Entity Framework work with our IEntity
interface?
推荐答案
我可以通过添加类
泛型类型约束扩展方法来解决这个问题。我不知道为什么它的工作原理,但。
I was able to resolve this by adding the class
generic type constraint to the extension method. I'm not sure why it works, though.
public static T GetById<T>(this IQueryable<T> collection, Guid id)
where T : class, IEntity
{
//...
}
这篇关于LINQ到实体仅支持铸造EDM基元或枚举类型与IEntity接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!