0

看完后,这个问题。我想我需要查看我的结构以避免冗余代码。

我当前的结构是 Controller -> Repository -> IRepository。

存储库如下所示:

public class UserRepository : IUserRepository, IDisposable
{
    private StudentSchedulingEntities _context;

    public UserRepository(StudentSchedulingEntities context)
    {
        if (context == null)
            throw new ArgumentNullException("context");

        _context = context;
    }
    public IEnumerable<User> GetUsers()
    {
        return _context.Users.ToList();
    }
    public User GetUserByID(int id)
    {
        return _context.Users.Find(id);

    }
    public void InsertStudent(User user)
    {
        _context.Users.Add(user);
    }
    public void DeleteStudent(int userID)
    {
        User usr = _context.Users.Find(userID);
        _context.Users.Remove(usr);
    }
    public void UpdateStudent(User user)
    {
        _context.Entry(user).State = EntityState.Modified;
    }
    public void Save() {
        _context.SaveChanges();
    }
    public void Dispose()
    {
        Dispose(true); 
        GC.SuppressFinalize(this); 
    }
    protected virtual void Dispose(bool disposing)
    {
        if (disposing)
        {
            if (_context != null)
            {
                _context.Dispose();
                _context = null;
            }
        }
    }
}

我的 IRepository 看起来像这样:

public interface IUserRepository : IDisposable
{
    IEnumerable<User> GetUsers();
    User GetUserByID(int userID);
    void InsertStudent(User user);
    void DeleteStudent(int userID);
    void UpdateStudent(User user);
    void Save();
}

我想避免在服务层再次这样做。我需要存储库类还是应该只实现服务层来替换存储库?

4

2 回答 2

2

您的服务层不需要任何存储库实现,它只需使用存储库来查找用户、添加/编辑/删除用户等。

现在,如果我能提供一些意见,我建议使用通用存储库。这样,如果您需要创建新的存储库,这真的很简单。我们使用 nopCommerce,他们使用以下代码:

public partial interface IRepository<T> where T : BaseEntity
{
    T GetById(object id);
    void Insert(T entity);
    void Update(T entity);
    void Delete(T entity);
    IQueryable<T> Table { get; }
}

由于它使用实体框架,因此这是实现:

/// <summary>
/// Entity Framework repository
/// </summary>
public partial class EfRepository<T> : IRepository<T> where T : BaseEntity
{
    private readonly IDbContext _context;
    private IDbSet<T> _entities;

    /// <summary>
    /// Ctor
    /// </summary>
    /// <param name="context">Object context</param>
    public EfRepository(IDbContext context)
    {
        this._context = context;
    }

    public T GetById(object id)
    {
        return this.Entities.Find(id);
    }

    public void Insert(T entity)
    {
        try
        {
            if (entity == null)
                throw new ArgumentNullException("entity");

            this.Entities.Add(entity);

            this._context.SaveChanges();
        }
        catch (DbEntityValidationException dbEx)
        {
            var msg = string.Empty;

            foreach (var validationErrors in dbEx.EntityValidationErrors)
                foreach (var validationError in validationErrors.ValidationErrors)
                    msg += string.Format("Property: {0} Error: {1}", validationError.PropertyName, validationError.ErrorMessage) + Environment.NewLine;

            var fail = new Exception(msg, dbEx);
            //Debug.WriteLine(fail.Message, fail);
            throw fail;
        }
    }

    public void Update(T entity)
    {
        try
        {
            if (entity == null)
                throw new ArgumentNullException("entity");

            this._context.SaveChanges();
        }
        catch (DbEntityValidationException dbEx)
        {
            var msg = string.Empty;

            foreach (var validationErrors in dbEx.EntityValidationErrors)
                foreach (var validationError in validationErrors.ValidationErrors)
                    msg += Environment.NewLine + string.Format("Property: {0} Error: {1}", validationError.PropertyName, validationError.ErrorMessage);

            var fail = new Exception(msg, dbEx);
            //Debug.WriteLine(fail.Message, fail);
            throw fail;
        }
    }

    public void Delete(T entity)
    {
        try
        {
            if (entity == null)
                throw new ArgumentNullException("entity");

            this.Entities.Remove(entity);

            this._context.SaveChanges();
        }
        catch (DbEntityValidationException dbEx)
        {
            var msg = string.Empty;

            foreach (var validationErrors in dbEx.EntityValidationErrors)
                foreach (var validationError in validationErrors.ValidationErrors)
                    msg += Environment.NewLine + string.Format("Property: {0} Error: {1}", validationError.PropertyName, validationError.ErrorMessage);

            var fail = new Exception(msg, dbEx);
            //Debug.WriteLine(fail.Message, fail);
            throw fail;
        }
    }

    public virtual IQueryable<T> Table
    {
        get
        {
            return this.Entities;
        }
    }

    private IDbSet<T> Entities
    {
        get
        {
            if (_entities == null)
                _entities = _context.Set<T>();
            return _entities;
        }
    }
        //TODO implement IDisposable interface
}

现在它就像IRepository<User>or一样简单IRepository<Whatever>

于 2012-05-14T17:57:30.740 回答
0

绝对不要冗余代码:-)当你说:

我当前的结构是 Controller -> Repository ->

控制器是从存储库继承的吗?你也不想这样。存储库层通常与存储(XML、数据库、文件系统等)接口并映射到存储库友好类。另一层管理存储库层到您的本机业务/服务类的映射。

于 2012-05-14T18:12:31.620 回答