【发布时间】:2011-08-05 20:49:35
【问题描述】:
我正在使用 POCO 开发原型 EF 应用程序。主要作为对框架的介绍,我想知道一种以良好结构设置应用程序的好方法。稍后我打算将 WCF 纳入其中。
我所做的如下:
1) 我创建了一个 edmx 文件,但代码生成属性设置为 None 并生成了我的数据库架构,
2) 我创建的 POCO 看起来都像:
public class Person
{
public Person()
{
}
public Person(string firstName, string lastName)
{
FirstName = firstName;
LastName = lastName;
}
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
3) 我创建了一个上下文
public class PocoContext : ObjectContext, IPocoContext
{
private IObjectSet<Person> persons;
public PocoContext() : base("name=PocoContainer", "PocoContainer")
{
ContextOptions.LazyLoadingEnabled = true;
persons= CreateObjectSet<Person>();
}
public IObjectSet<Person> Persons
{
get
{
return persons;
}
}
public int Save()
{
return base.SaveChanges();
}
}
界面如下:
public interface IPocoContext
{
IObjectSet<Person> Persons { get; }
int Save();
}
4) 最后我创建了一个存储库,实现了一个接口:
public class PersonRepository : IEntityRepository<Person>
{
private IPocoContext context;
public PersonRepository()
{
context = new PocoContext();
}
public PersonRepository(IPocoContext context)
{
this.context = context;
}
// other methods from IEntityRepository<T>
}
public interface IEntityRepository<T>
{
void Add(T entity);
List<T> GetAll();
T GetById(int id);
void Delete(T entity);
}
现在,当我开始玩这个时,这个设计要求我每次想要获取或改变一些数据时都要实例化一个存储库,如下所示:
using (var context = new PocoContext())
{
PersonRepository prep = new PersonRepository();
List<Person> pers = prep.GetAll();
}
另一方面,在派生上下文中实例化每个存储库也感觉不太好,因为可能会实例化我可能根本不需要的对象。
关于如何使这个设计听起来不错的任何提示?我应该这样吗?这样做时我应该添加或避免什么?
【问题讨论】:
-
是什么样的应用程序。 Web 服务、WPF 应用程序,还有什么?
-
在这种状态下它只是一个控制台应用程序,因为它只是一个最低限度的原型。
-
我问的原因是你如何处理你的上下文很大程度上受应用程序类型的影响。例如,在 wpf 应用程序中每个表单有一个上下文,在 Web 应用程序中每个 http 请求有一个上下文,在 Web 服务中每个方法调用有一个上下文,这是很常见的。
-
本练习的最终目标是了解 EF 和 WCF,因此在我正确设置后,我会将其重构为以 WCF 为中心的应用程序。
标签: c# .net entity-framework architecture structure