Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / web / ASP.NET / ASP.NET5

My DAL Design--- ASP.NET MVC

3.00/5 (5 votes)
21 Mar 2016CPOL2 min read 26.7K  
Repository Pattern with Generic Interface and Dependency Injection

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.

C#
  "Dboperation": {

    "Stylename": "Entityframeworkdal" /* Adonetdal、nhibernatedal(whatever Name You like)*/

  },
// 1.config file way------------get config

       DBOStyle= Configuration["DBOperation:stylename"];
       apppath = AppDomain.CurrentDomain.SetupInformation.ApplicationBase;
       appname = Assembly.GetExecutingAssembly().GetName().Name;

 //2.system injection way--- ---creat your container of dependency injection
       container  = new UnityContainer();
       container.RegisterType(typeof(IBaseDAL<>), typeof(EntityFrameworkDAL<> )  );

二、define  console 、interface and implementation class

C#
public class SetDBOStyle<T> where T  : class  //---------identify the dbo style 
   {   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
    {
        //-----------according to EntityFrameworkDAL parameter<T>to gain  data of  a table-----------
       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();

                //---------------convert  model  to basemodel-----------
                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
       {//repeat above function define with ado.net techique}

        public class NHIBERNATEDAL<T> : IBaseDAL<T> where T : class
       {/repeat above function define with NHIBERNATE techique}

  }

三、invoke in controller

C#
public IActionResult Index( )--------------controller
        {
            //-----------------------invoke method one------
           //*   Idboperation = (IBaseDAL<people>)SetDBOStyle<people>.CreateDAL();*/

            //-----------------------invoke method two
            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.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)