Click here to Skip to main content
16,007,885 members
Articles / Web Development / ASP.NET / ASP.NETvNext

My DAL Design--- ASP.NET MVC

Rate me:
Please Sign up or sign in to vote.
3.00/5 (5 votes)
21 Mar 2016CPOL2 min read 26.6K   11   7
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)


Written By
Unknown
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionFail to see the point Pin
Kirk Wood29-Mar-16 6:26
Kirk Wood29-Mar-16 6:26 
First, I have personally yet to see a project change from one data access to another in the manner you seem concerned about. And further, few developers I know have either. Good example of what is NOT likely to change to me. (And I have only spoken to a single developer who had the task of changing ORMs.)

Second, I don't see anything that will really save you that much. In fact, I would guess that this will cause more issues than it solves because now you will be fetching everything in an entire table every time. What I have seen in most projects that move beyond very simple is that the model as expressed to a view needs to be different from the model as expressed in the database. And too many working with any ORM. The simple fact is that a good database model doesn't make for a good business logic model. It never seems long before I find myself projecting ORM queries into classes that are not known to the ORM.

Finally, your dependency injection became a mess. After initial configuration, most of your concern with the IOC should be done. When you call your IOC, it is a code smell. For any ASP.NET any and all initialization should occur from a call in Global.ascx. Then your controller should simply express a dependency through its constructor. My guess is that you have not used a popular IOC with their stock integration packages.

AnswerRe: Fail to see the point Pin
Jamescookxj22-Sep-16 21:58
Jamescookxj22-Sep-16 21:58 
GeneralMy vote of 1 Pin
Henrique C.28-Mar-16 3:19
professionalHenrique C.28-Mar-16 3:19 
GeneralRe: My vote of 1 Pin
Jamescookxj22-Sep-16 22:03
Jamescookxj22-Sep-16 22:03 
GeneralMy vote of 1 Pin
jtmueller22-Mar-16 6:58
jtmueller22-Mar-16 6:58 
GeneralRe: My vote of 1 Pin
Jamescookxj22-Mar-16 11:16
Jamescookxj22-Mar-16 11:16 
GeneralRe: My vote of 1 Pin
jtmueller22-Mar-16 12:01
jtmueller22-Mar-16 12:01 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.