using System; using System.Data.Entity; using EnVisage.Models; using NLog; namespace EnVisage.Code.BLL { public class ManagerBase: IDisposable where TDALClass : class, new() where TModel : IBaseModel, new() { private readonly EnVisageEntities _dbContext; private readonly bool _isContexLocal; protected readonly Logger Logger = LogManager.GetCurrentClassLogger(); protected EnVisageEntities DbContext => _dbContext; public virtual DbSet DataTable { get { throw new NotImplementedException(); } } protected bool IsContextLocal => _isContexLocal; public ManagerBase(EnVisageEntities dbContext) { if (dbContext == null) { _dbContext = new EnVisageEntities(); _isContexLocal = true; } else { _dbContext = dbContext; } } public void Dispose() { if (_isContexLocal) _dbContext.Dispose(); } #region Public Methods /// /// Loads a TDALClass from the database. /// /// Unique identifier of the TDALClass. /// Indicates that object will not be saved later in the code. Use false if you need to save an updated object. /// A object retrieved from database. public virtual TDALClass Load(Guid? value, bool isReadOnly = true) { if (value == null || value == Guid.Empty) return new TDALClass(); return isReadOnly ? RetrieveReadOnlyById(value.Value) : DataTable.Find(value); } /// /// Retrieves a readonly DAL object from database. /// /// An instance of class. protected virtual TDALClass RetrieveReadOnlyById(Guid key) { throw new NotImplementedException(); } /// /// Saves an instance of the into the database. /// /// A model object with data from the form. public virtual TDALClass Save(TModel model) { if (model == null) throw new ArgumentNullException(nameof(model)); #region Save data TDALClass dbObj = null; bool newDbObject = false; if (model.Id != Guid.Empty) dbObj = DataTable.Find(model.Id); if (dbObj == null) { newDbObject = true; dbObj = InitInstance(); } model.CopyTo(dbObj); if (model.Id == Guid.Empty || newDbObject) { DataTable.Add(dbObj); } else _dbContext.Entry(dbObj).State = EntityState.Modified; #endregion if (_isContexLocal) _dbContext.SaveChanges(); return dbObj; } /// /// Creates an instance of the class and initializes it. /// /// An instance of the class. protected virtual TDALClass InitInstance() { return new TDALClass(); } #endregion } }