Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class UnitOfWork : IUnitOfWork
- {
- public DbContext Context { get; private set; }
- public UnitOfWork(DbContext context)
- {
- Context = context;
- }
- public void Commit()
- {
- if(Context != null)
- {
- try
- {
- Context.SaveChanges();
- }
- catch(DbEntityValidationException exc)
- {
- foreach (var eve in exc.EntityValidationErrors)
- {
- Debug.WriteLine("Entity of type "{0}" in state "{1}" has the following validation errors:",
- eve.Entry.Entity.GetType().Name, eve.Entry.State);
- foreach (var ve in eve.ValidationErrors)
- {
- Debug.WriteLine("- Property: "{0}", Error: "{1}"",
- ve.PropertyName, ve.ErrorMessage);
- }
- }
- throw;
- }
- }
- }
- public void Dispose()
- {
- Dispose(true);
- GC.SuppressFinalize(this);
- }
- public void Dispose(bool disposing)
- {
- if(!disposed)
- {
- if(disposing)
- {
- // free managed objects
- }
- // free unmanaged objects
- Context?.Dispose();
- disposed = true;
- }
- }
- ~UnitOfWork()
- {
- if(!disposed)
- {
- Dispose(false);
- }
- }
- private bool disposed = false;
- }
- public class UserRepository : IUserRepository
- {
- public UserRepository(DbContext context)
- {
- this.context = context;
- this.unitOfWork = new UnitOfWork(context);
- }
- public void Create(DalUser entity)
- {
- if (entity == null)
- throw new ArgumentNullException(nameof(entity));
- User ormUser = entity.ToOrmUser();
- context?.Set<User>().Add(ormUser);
- unitOfWork.Commit();
- }
- public void Update(DalUser entity)
- {
- if (entity == null)
- throw new ArgumentNullException(nameof(entity));
- User ormUser = context?.Set<User>().FirstOrDefault(u => u.Id == entity.Id);
- if(ormUser != null)
- {
- ormUser.Nickname = entity.Nickname;
- ormUser.Password = entity.Password;
- }
- unitOfWork.Commit();
- }
- public void Delete(DalUser entity)
- {
- if (entity == null)
- throw new ArgumentNullException(nameof(entity));
- User ormUser = context?.Set<User>().FirstOrDefault(u => u.Id == entity.Id);
- if (ormUser != null)
- context?.Set<User>().Remove(ormUser);
- unitOfWork.Commit();
- }
- public IEnumerable<DalUser> GetAll() => context?.Set<User>().ToList().Select(u => u.ToDalUser());
- public DalUser GetById(int id) => context?.Set<User>().FirstOrDefault(u => u.Id == id)?.ToDalUser();
- public DalUser GetUserByNickname(string nickname) => context?.Set<User>().FirstOrDefault(u => u.Nickname == nickname)?.ToDalUser();
- private readonly DbContext context;
- private readonly IUnitOfWork unitOfWork;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement