[英]Entity Framework with a layered web application
我知道这个问题似乎已经在这里提出了,但是我有具体的疑问, 主要是数据库优先使用和回答问题中缺少代码示例。
我有以下几层:核心,数据和UI(asp.net mvc)。 我在MSSQL中有这些表:人员和联系人。
问题1:在数据层中,EDMX生成人员和数据POCO。 我在哪里编写类似SearchPersonByCity()
方法? 我是否需要在同一数据层中创建另一个Person类,仅用于编写数据CRUD? 我怎么做的? 请举一个例子(类,名称空间等。不需要完整的实际代码)
问题2:如何在数据层和核心(域模型)之间转换这些数据? 在核心(域)类中,我需要在哪里创建相同的SearchPersonByCity()
? 也许只为这些数据访问方法在核心层中创建另一个Person类?
请给我一些代码示例,以及大公司在现实生活中的表现,因为它似乎太笨了,要维护和麻烦的代码很多,我弄错了。
我并不懒惰,我阅读了数百页的Entity Framework书籍,这里有问题,而且我不知道如何在代码中做到这一点。
我认为我将在您的情况下使用存储库模式,因此首先您需要定义一个IRepository类:
public interface IRepository<T> where T :
{
void Add(T entity);
void Update(T entity);
void Delete(T entity);
void Delete(Expression<Func<T, bool>> where);
T GetById(long id);
T GetById(string id);
T Get(Expression<Func<T, bool>> where);
}
还有一个抽象的基础RepositoryBase类:
public abstract class RepositoryBase<T> where T : class
{
private PersonDBEntities dataContext;
private readonly IDbSet<T> dbset;
protected RepositoryBase(IDatabaseFactory databaseFactory)
{
DatabaseFactory = databaseFactory;
dbset = DataContext.Set<T>();
}
protected IDatabaseFactory DatabaseFactory
{
get;
private set;
}
protected PersonDBEntities DataContext
{
get { return dataContext ?? (dataContext = DatabaseFactory.Get()); }
}
public virtual void Add(T entity)
{
dbset.Add(entity);
}
public virtual void Update(T entity)
{
dbset.Attach(entity);
dataContext.Entry(entity).State = EntityState.Modified;
}
public virtual void Delete(T entity)
{
dbset.Remove(entity);
}
public virtual void Delete(Expression<Func<T, bool>> where)
{
IEnumerable<T> objects = dbset.Where<T>(where).AsEnumerable();
foreach (T obj in objects)
dbset.Remove(obj);
}
public virtual T GetById(long id)
{
return dbset.Find(id);
}
public virtual T GetById(string id)
{
return dbset.Find(id);
}
public virtual IEnumerable<T> GetAll()
{
return dbset.ToList();
}
//You can return IQueryable if you want to build your expression true later on...
public virtual IEnumerable<T> Get(Expression<Func<T, bool>> where)
{
return dbset.Where(where).ToList();
}
}
和您的PersonRepository类:
public class PersonRepository: RepositoryBase<Person>, IPersonRepository
{
public PersonRepository(IDatabaseFactory databaseFactory)
: base(databaseFactory)
{
}
}
public interface IPersonRepository : IRepository<Person> // Person will be your POCO class
{
}
下一步是在服务层上,您将定义并实现实际的SearchPersonByCity()方法:
public class PersonService : IPersonService
{
private readonly IPersonRepository personRepository;
private readonly IUnitOfWork unitOfWork;
public PersonService(IPersonRepository personRepository, IUnitOfWork unitOfWork)
{
this.personRepository = personRepository;
this.unitOfWork = unitOfWork;
}
public IEnumerable<Person> SearchPersonByCity(string city)
{
var persons = personRepository.Get(p => p.City == city);
return persons;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.