using Bro.M071.Model;
|
using System.Collections.Generic;
|
using System.Configuration;
|
using System.Data.Entity;
|
using System.Linq;
|
using System.Reflection;
|
|
namespace Bro.M071.DBManager
|
{
|
public class ModelManager<T> where T : BaseModel, new()
|
{
|
private PropertyInfo TableProperty = null;
|
public static string ConnectionString = ConfigurationManager.ConnectionStrings["DataBase"].ConnectionString;
|
public ModelManager()
|
{
|
T t = new T();
|
using (DBModel db = new DBModel())
|
{
|
TableProperty = db.GetType().GetProperties().FirstOrDefault(u => u.Name == t.GetType().Name);
|
}
|
}
|
|
public void CreateModel(T t, string userId = "")
|
{
|
using (DBModel context = new DBModel())
|
{
|
ActionBeforeNewModel(context, t);
|
|
t.Create(userId);
|
(TableProperty.GetValue(context) as DbSet<T>).Add(t);
|
|
context.SaveChanges();
|
}
|
}
|
|
public void BatchAdd(List<T> t, string userId = "")
|
{
|
using (DBModel context = new DBModel())
|
{
|
(TableProperty.GetValue(context) as DbSet<T>).AddRange(t);
|
context.SaveChanges();
|
}
|
}
|
|
public void UpdateModel(T t, string userId = "")
|
{
|
using (DBModel context = new DBModel())
|
{
|
ActionBeforeUpdateModel(context, t);
|
|
DbSet<T> set = TableProperty.GetValue(context) as DbSet<T>;
|
T oldT = set.FirstOrDefault(u => u.ID == t.ID);
|
|
oldT.DataTransfer(t);
|
oldT.Update(userId);
|
context.SaveChanges();
|
}
|
}
|
|
public void DeleteModel(string id, bool isDelete = true, string userId = "")
|
{
|
using (DBModel context = new DBModel())
|
{
|
ActionBeforeDeleteModel(context, id);
|
|
DbSet<T> set = TableProperty.GetValue(context) as DbSet<T>;
|
T oldT = set.FirstOrDefault(u => u.ID == id);
|
oldT.IS_DELETED = isDelete ? 1 : 0;
|
oldT.Update(userId);
|
|
context.SaveChanges();
|
}
|
}
|
|
public void DisableModel(string id, bool isDisable = true, string userId = "")
|
{
|
using (DBModel context = new DBModel())
|
{
|
ActionBeforeEnableModel(context, id);
|
|
DbSet<T> set = TableProperty.GetValue(context) as DbSet<T>;
|
T oldT = set.FirstOrDefault(u => u.ID == id);
|
oldT.IS_DISABLED = isDisable ? 1 : 0;
|
oldT.Update(userId);
|
|
context.SaveChanges();
|
}
|
}
|
|
#region ""
|
protected virtual void ActionBeforeNewModel(DBModel context, T t)
|
{
|
}
|
|
protected virtual void ActionBeforeUpdateModel(DBModel context, T t)
|
{
|
}
|
|
protected virtual void ActionBeforeDeleteModel(DBModel context, string id)
|
{
|
}
|
|
protected virtual void ActionBeforeEnableModel(DBModel context, string id)
|
{
|
}
|
#endregion
|
}
|
}
|