次の一般的な拡張メソッドがあります。
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 は を処理する方法を知りません。
e => ((IEntity)e).Id == id
Entity Framework は次の例外をスローします。
タイプ「IEntity」をタイプ「SomeEntity」にキャストできません。LINQ to Entities は、EDM プリミティブ型または列挙型のキャストのみをサポートします。
Entity Framework をインターフェイスで動作させるにはどうすればよいIEntity
でしょうか?