我正在尝试使用通用存储库模式(部分基于本文),在尝试将业务逻辑层和数据层分开时,我遇到了困惑。
这是我的存储库界面,位于业务逻辑程序集中:
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);
}
这是我的数据层程序集中的concreate存储库类:
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;
}
}
来自bussines逻辑的服务看起来像这样:
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)。
这是否意味着我需要将每个业务对象映射到数据层中的数据对象?
我不确定我是否正确接近它,如果我这样做,我应该如何进行映射?因为我也坚持这一点,这让我觉得我接近错了。
答案 0 :(得分:1)
在我个人看来,我不建议您将您的商业模式用作您的视图模型。有关详细信息,请查看此link。
关于如何进行对象映射:检查Automapper,它是一个不错的工具,您可以在Github上找到documentation,并在this上找到很多教程互联网!
问候。