【发布时间】:2011-06-03 14:14:35
【问题描述】:
我的 Entity Framework 4 项目中有一个“客户”POCO 实体。我想将我的客户实体作为通用列表而不是 ObjectSet 公开给我的上层。
我有一个 IUnitOfWork 接口,如下所示:
public interface IUnitOfWork
{
string Save();
IList<Customer> Customers { get; }
}
在我的实体框架 DAL(实现上述接口)我有以下内容:
public class EntityContainer : ObjectContext, IUnitOfWork
{
private IObjectSet<Customer> _customers;
public IList<Customer> Customers
{
get
{
if (_customers == null)
{
_customers = CreateObjectSet<Customer>("Customers");
}
return _customers.ToList<Customer>() ;
}
}
}
但是,'CreateObjectSet("Customers")' 行不起作用。每次我尝试添加新的“客户”时,什么都没有发生。有趣的是,如果我恢复使用 IObjectSet,那么代码就可以工作。例如:
public interface IUnitOfWork
{
string Save();
IObjectSet<Contact> Contacts { get; }
}
public class EntityContainer : ObjectContext, IUnitOfWork
{
private IObjectSet<Customer> _customers;
public IObjectSet<Customer> Customers
{
get
{
if (_customers == null)
{
_customers = CreateObjectSet<Customer>("Customers");
}
return _customers;
}
}
}
IQueryable 也可以工作,但我无法让 IList 工作,我也不知道为什么。有人有什么想法吗?
#
对原始问题的更正。使用 IQueryable 不起作用,IEnumerable 也不起作用。这是因为客户存储库需要提供“添加”和“删除”方法来从实体集合中添加/删除(在上面的示例中添加或删除客户实体)。 IQueryable 或 IEnumerable 都不允许您添加或删除对象;相反,必须使用 ICollection 或 IList。这让我回到了原来的问题。我不想将我的集合作为 ObjectSet 公开给存储库。我想使用与 EntityFramework 无关的类型,即 - 我想使用通用列表。
还有其他建议吗?我怀疑有一种简单的方法可以做到这一点,但我对框架不够熟悉,无法弄清楚。
【问题讨论】:
-
IEnumerable<T>更加通用。
标签: c# entity-framework-4 iqueryable