Why do we need a DAL?
Before, using the ADO.NET to access and operate databases. The DAL is used to standardize and package DB operation classes and the major goal is to realize the operation factorization of all kinds of DB . After we moved to Entity Framework to operate DB, we used the ORM to operate DB. But I think that it is still necessary to decouple the business logic layer and the method of operation DB(such as EF ) . After all,maybe sometime, there will be a new kind of skill instead of EF . You could not image that you will check your all BLL layer of cs files to replace all Dbcontext objects and other EF of things with a new emerging of technology. In another situation, depending on some differdent requirement circumstance, you maybe need to change your EF to Nhhibernate or Ado.net in your project. So,I want to make a persistent database access layer to operate data.
Introduction
ASP.NET MVC framework is base on Generic 、denpendence injection
Normally I adapt interface repository pattern to make the DAL. In the webform period, we commonly initialize a project from DB design. When using MVC ,we code with Model oriented. Consequently, in the view of CSHTML files and the DAL cs files, we all need to know what table or model data that we want to get or send. so ,the generic is a good way to use. Dependency Injection is a better system way to help us locate the implementation class . Of course,you can code that by yourself as the past method that we used.
say too much , show my code
一、gain config in public class Startup
If you want use the config file to dentify what kind of DB Operation style that you want, you might add the code into your config or json file. You might ignore the code if you want to use system denpendence injection.
"Dboperation": {
"Stylename": "Entityframeworkdal"
},
DBOStyle= Configuration["DBOperation:stylename"];
apppath = AppDomain.CurrentDomain.SetupInformation.ApplicationBase;
appname = Assembly.GetExecutingAssembly().GetName().Name;
container = new UnityContainer();
container.RegisterType(typeof(IBaseDAL<>), typeof(EntityFrameworkDAL<> ) );
二、define console 、interface and implementation class
public class SetDBOStyle<T> where T : class
{ private static readonly string DBOStylename = Startup.DBOStyle;
private SetDBOStyle() { }
public static object CreateDAL()
{
try
{
string a = System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Namespace;
string b = a + '.' + DBOStylename + "`1[" + typeof(T).ToString() + "]";
Type DBOStyleClass = Type.GetType(b);
object pp = Activator.CreateInstance(DBOStyleClass);
return pp ;
}
catch (Exception ex)
{
throw new Exception(ex.Message.ToString());
}
}
} public interface IBaseDAL <T> where T :class
{
IList<basemodel> ReturnATableData();
}
public class EntityFrameworkDAL<T> : IBaseDAL<T> where T : class
{
public IList<basemodel> ReturnATableData()
{
try
{
var dbContext = new MyContext();
IDatabaseInitializer<MyContext> dbInitializer = null;
if (dbContext.Database.Exists())
{
dbInitializer = new DropCreateDatabaseIfModelChanges<MyContext>();
}
else
{
dbInitializer = new DropCreateDatabaseAlways<MyContext>();
}
Database.SetInitializer(dbInitializer);
List<T> resultlist = new List<T>();
Type Tablemodelclass = System.Type.GetType(typeof(T).ToString(), true);
DbSet aa = dbContext.Set(Tablemodelclass);
foreach (var item in aa)
{
resultlist.Add((T)item);
}
dbContext.Dispose();
List<basemodel> pp = new List<basemodel>();
BaseLibrary<basemodel, T>.DALmodeltoVIEWmodel(ref pp, resultlist);
return (pp);
}
catch (Exception ex)
{
throw new Exception(ex.Message.ToString());
}
}
public class ADONETDAL<T> : IBaseDAL<T> where T : class
{
public class NHIBERNATEDAL<T> : IBaseDAL<T> where T : class
{/repeat above function define with NHIBERNATE techique}
}
三、invoke in controller
public IActionResult Index( )--------------controller
{
Idboperation = Startup.container.Resolve<IBaseDAL<people>>();
if (Idboperation != null)
{
IList<basemodel> temp = Idboperation.ReturnATableData();
List<people> PP = new List<people>();
BaseLibrary<people, basemodel>.DALmodeltoVIEWmodel(ref PP, temp);
return View(PP);
}
return View();
}
Conclusion
Through the using DAL layer ,we unify and standerdize the databse access library. Avoiding code include direct useing a lot of EF objects and induce deal of repeat work of database operation . When we have to modify and replace database access class ,we only need to revise our DAL code. Dependency injection is very well way to identify the implementation class of interface.