【发布时间】:2011-08-29 23:01:48
【问题描述】:
我有以下代码:
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 的提供程序会按类型解析给定的表达式 first 或 default 。 id 的类型是 TKey,它不是 typeof(Guid)。
-
我相信 TDaver 是对的。如果您有一个非泛型参数
Guid而不是泛型TKey参数,则该代码实际上可以工作。
标签: entity-framework generics ado.net repository-pattern