【发布时间】:2016-01-05 02:03:59
【问题描述】:
我正在尝试使用通用存储库模式(部分基于本文)并且在尝试分离我的业务逻辑层和我的数据层时遇到了困惑。
这是我的存储库接口,位于业务逻辑组件中:
public interface IRepository<TEntity> where TEntity : class
{
/// <summary>
/// Get one entity based on its Identifier.
/// </summary>
TEntity Get(object id);
/// <summary>
/// Get one entity based on provided criteria.
/// </summary>
TEntity GetOne(Expression<Func<TEntity, bool>> where = null);
/// <summary>
/// Finds entities based on provided criteria.
/// </summary>
IQueryable<TEntity> GetAll(Expression<Func<TEntity, bool>> where = null);
/// <summary>
/// Insert the existing entity.
/// </summary>
void Insert(TEntity model);
/// <summary>
/// Deletes the existing entity.
/// </summary>
void Delete(long id);
/// <summary>
/// Updates the existing entity.
/// </summary>
void Update(TEntity model);
}
这是我在数据层程序集中创建的存储库类:
public class EfRepository<TEntity> : IRepository<TEntity>, IDisposable
where TEntity : class, new()
{
private readonly DbContext _context;
private DbSet<TEntity> _entities;
internal EfRepository(DbContext context)
{
_context = context;
}
private DbSet<TEntity> Entities
{
get { return _entities ?? (_entities = _context.Set<TEntity>()); }
}
public TEntity Get(object id)
{
return Entities.Find(id);
}
public void Insert(TEntity entity)
{
Entities.Add(entity);
Save();
}
public void Delete(long id)
{
var entity = Get(id);
Delete(entity);
}
private void Delete(TEntity entity)
{
Entities.Remove(entity);
Save();
}
public IList<TEntity> Table
{
get { return Entities.ToList(); }
}
public void Update(TEntity entity)
{
_context.Entry(entity).State = System.Data.EntityState.Modified;
Save();
}
private void Save()
{
_context.SaveChanges();
}
public void Dispose()
{
_context.Dispose();
}
public TEntity GetOne(System.Linq.Expressions.Expression<Func<TEntity, bool>> where = null)
{
return GetAll(where).FirstOrDefault();
}
public IQueryable<TEntity> GetAll(System.Linq.Expressions.Expression<Func<TEntity, bool>> where = null)
{
return null != where ? Entities.Where(where) : Entities;
}
}
业务逻辑中的服务如下所示:
public class UserService : IUserService
{
private IRepository<User> _userRepository;
public UserService(IRepository<User> userRepository)
{
_userRepository = userRepository;
}
public void Register(User user)
{
//some logic goes here
_userRepository.Insert(user);
}
}
现在的问题是我不希望我的业务逻辑知道数据层,这意味着 TEntity 应该是一个业务对象(如本例中的 User)。
这是否意味着我需要将每个业务对象映射到数据层中的数据对象?
我不确定我是否正确地接近它,如果我这样做了,我应该如何进行映射?因为我也坚持这一点,这让我认为我接近它是错误的。
【问题讨论】:
-
通过 Data Transfer Object 而不是业务层中的实体。
-
我建议看看stackoverflow.com/questions/29002546/…。你BL不应该知道DL。但是你的 DL 会知道 BL。如果您知道依赖注入,那么这将很容易理解和实施。否则你需要得到这本书(manning.com/books/dependency-injection-in-dot-net)