如何使用 Entity Framework 4 和存储库模式实现通用 GetById 方法?
我有一个通用存储库,并且想实现一个通用 GetById 方法。到目前为止,这是我的存储库界面:
public interface IRepository<T> where T : EntityObject
{
void Add(T entity);
void Delete(int id);
void Delete(T entity);
IEnumerable<T> Find(Expression<Func<T, bool>> predicate);
T SingleOrDefault(Expression<Func<T, bool>> predicate);
IEnumerable<T> GetAll();
T GetById(int id);
void Save();
T Single(Expression<Func<T, bool>> predicate);
}
我正在使用实体框架 4.1。我发现的许多解决方案都使用 IEntity 类的接口的抽象基类,实体必须继承该类才能执行 Id 查找。
我尝试使用这段代码,而不是必须为所有类实现一个接口:
T entity = _objectSet.Where(
x => x.EntityKey.EntityKeyValues
.Select(v => v.Value.Equals(id)).Count() == 1).First();
但是,当尝试使用该方法时,我收到一个异常:
LINQ to Entities 不支持指定的类型成员“EntityKey” 。仅支持初始值设定项、实体成员和实体导航属性。
有人可以告诉我如何让它工作吗?
更新 1
成员 _objectContext 和 _context 声明如下:
private readonly ObjectContext _context;
private readonly IObjectSet<T> _objectSet;
谢谢。
I have a generic repository and would like to implement a generic GetById method. This is my repository interface so far:
public interface IRepository<T> where T : EntityObject
{
void Add(T entity);
void Delete(int id);
void Delete(T entity);
IEnumerable<T> Find(Expression<Func<T, bool>> predicate);
T SingleOrDefault(Expression<Func<T, bool>> predicate);
IEnumerable<T> GetAll();
T GetById(int id);
void Save();
T Single(Expression<Func<T, bool>> predicate);
}
I am using the Entity Framework 4.1. Lots of the solutions I found were using an abstract base class of interface for an IEntity class which the entities have to inherit from in order to perform the Id lookup.
Instead of having to implement an interface for all my classes I was trying to use this bit of code:
T entity = _objectSet.Where(
x => x.EntityKey.EntityKeyValues
.Select(v => v.Value.Equals(id)).Count() == 1).First();
However when trying to use the method I receive an exception:
The specified type member 'EntityKey' is not supported in LINQ to Entities. Only initializers, entity members, and entity navigation properties are supported.
Could someone tell me how I can get this to work?
Update 1
The members _objectContext and _context are declared like this:
private readonly ObjectContext _context;
private readonly IObjectSet<T> _objectSet;
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
从这个问题 如何获取 ObjectSet的实体键名称?,你可以稍微作弊一下并使用ESQL。
我已经在方法中包含了所有需要的代码,显然您想稍微重构它,但它应该适合您。
From this question How to get ObjectSet<T>'s entity key name?, you can cheat a little and use ESQL.
I've included all the needed code in the method, obviously you want to refactor it a little, but it should work for you.
对于那些“幸运”能够在 VB.net 中工作并且正在努力获取有效示例的人:
For those who are "lucky" enough to work in VB.net and you are struggling to get a working example: