EnVisageOnline/Main-RMO/Source/EnVisage/Code/BLL/ManagerBase.cs

110 lines
3.5 KiB
C#

using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;
using EnVisage.Models;
namespace EnVisage.Code.BLL
{
public class ManagerBase<TDALClass, TModel> where TDALClass : class, new() where TModel : IBaseModel<TDALClass>, new()
{
private readonly EnVisageEntities _dbContext;
private readonly bool _isContexLocal = false;
protected EnVisageEntities DbContext { get { return _dbContext; } }
public virtual DbSet<TDALClass> DataTable
{
get { throw new NotImplementedException(); }
}
protected bool IsContextLocal
{
get { return _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
/// <summary>
/// Loads a TDALClass from the database.
/// </summary>
/// <param name="value">Unique identifier of the TDALClass.</param>
/// <param name="isReadOnly">Indicates that object will not be saved later in the code. Use <b>false</b> if you need to save an updated object.</param>
/// <returns>A <see cref="TDALClass"/> object retrieved from database.</returns>
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);
}
/// <summary>
/// Retrieves a readonly DAL object from database.
/// </summary>
/// <returns>An instance of <see cref="TDALClass"/> class.</returns>
protected virtual TDALClass RetrieveReadOnlyById(Guid key)
{
throw new NotImplementedException();
}
/// <summary>
/// Saves an instance of the <see cref="TDALClass"/> into the database.
/// </summary>
/// <param name="model">A model object with data from the form.</param>
public virtual TDALClass Save(TModel model)
{
if (model == null)
throw new ArgumentNullException("model");
#region Save data
TDALClass dbObj = null;
if (model.Id != Guid.Empty)
dbObj = DataTable.Find(model.Id);
if (dbObj == null)
{
dbObj = InitInstance();
}
model.CopyTo(dbObj);
if (model.Id == Guid.Empty)
{
DataTable.Add(dbObj);
}
else
_dbContext.Entry(dbObj).State = EntityState.Modified;
#endregion
if (_isContexLocal)
_dbContext.SaveChanges();
return dbObj;
}
/// <summary>
/// Creates an instance of the <see cref="TDALClass"/> class and initializes it.
/// </summary>
/// <returns>An instance of the <see cref="TDALClass"/> class.</returns>
protected virtual TDALClass InitInstance()
{
return new TDALClass();
}
#endregion
}
}