通用库通过ID在EF4选择 [英] Generic repository select by ID in EF4

查看:189
本文介绍了通用库通过ID在EF4选择的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我想创建由ID方法的通用选择了一个基础库类。为了达到这个我使用POCO用的EF4。我创建了一个名为Id和成功,以在所有返回的PK实体通用Id属性修改的T4模板吸气的接口。

So I'm trying to create a generic select by ID method for a base repository class. In order to achieve this I'm using EF4 with POCO's. I created an interface with a getter called Id and successfully modified the T4 template in order to have a generic Id property in all the entities that returns the PK.

问题来了当我使用的查询。我采取这样的:

The problem comes when I use the query. I'm implementing it like this:

public virtual T GetByID(int id)
{
    return Database.ObjectSet<T>().SingleOrDefault(entity => entity.Id == id);
}

和即使在对象集返回的所有实体具有Id属性设置他们目前的主键值,我发现了一个奇怪的错误:

And even though all the entities returned by the ObjectSet have the Id property set with their current primary key value, I'm getting a weird error:

指定的类型成员ID不
支持在LINQ到实体。只有
初始值,实体成员和
实体导航属性都支持

The specified type member 'Id' is not supported in LINQ to Entities. Only initializers, entity members, and entity navigation properties are supported.

我是失去了一些东西?

推荐答案

如果通用标识只是(你提到)返回的PK,但实际上并没有映射到,PK本身,那么有没有办法让EF将其转换为SQL查询

If the generic Id only (as you mention) "returns the PK" but is not actually mapped to the PK itself, then there is no way for EF to convert this to a SQL query.

我已经在过去使用的一个模式:如果您所有的实体将有一个int PK名为id,那么你可以拥有所有的人都从一些基类,其中的ID属性定义(并映射到),并继承然后where子句添加到您的泛型方法:

One pattern I've used in the past: if all of your entities will have an int PK called Id then you can have all of them inherit from some baseclass where that Id property is defined (and mapped to) and then add a where clause to your generic method:

public virtual T GetByID(int id) where T : EntityBaseClass

仅供参考,我还与不同类型的使用泛型的PK实体用这个。

FYI, I've also used this with entities with different types of PKs using generics.

这篇关于通用库通过ID在EF4选择的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆