我有以下代碼:實體框架,LINQ和泛型
public interface IKeyed<TKey>
{
TKey Id { get; }
}
// This is the entity framework generated model. I have added the
// IKeyed<Guid> interface
public partial class Person : IKeyed<Guid>
{
public Guid Id { get; set; }
}
public class Repository<TKey, TEntity> : IKeyedRepository<TKey, TEntity>
where TEntity : class, IKeyed<TKey>
{
private readonly IObjectSet<TEntity> _objectSet;
public Repository(IOjectSet<TEntity> objectSet)
{
_objectSet = objectSet;
}
public TEntity FindBy(TKey id)
{
return _objectSet.FirstOrDefault(x => x.Id.Equals(id));
}
}
[更新] 這是我如何打電話這一點:
Db2Entities context = new Db2Entities(_connectionString); // This is the EF context
IObjectSet<Person> objectSet = context.CreateObjectSet<Person>();
IKeyedRepository<Guid, Person> repo = new Repository<Guid, Person>(objectSet);
Guid id = Guid.NewGuid();
Person person = repo.FindBy(id); // This throws the exception.
上面的代碼編譯。執行'FindBy'方法時,出現以下錯誤:
無法創建類型爲'閉包類型'的常量值。在此上下文中僅支持基本類型(例如Int32,String和Guid)。
由於我的'Id'的類型是一個Guid(支持的基本類型之一),似乎我應該能夠按摩這個工作。
任何人都知道這是可能的嗎?
感謝,
鮑勃
如果我必須通過我的冒險來判斷寫入linq提供者的東西,我假設EF的提供者分析首先給出的表達式或默認的類型。而id的類型是不是typeof(Guid)的TKey。 – TDaver 2011-05-20 20:48:51
我相信TDaver是對的。如果你有一個非泛型參數'Guid'而不是泛型'TKey'參數,那麼代碼實際上可以工作。 – Slauma 2011-05-21 12:24:24