Click here to Skip to main content
15,884,724 members
Articles / Programming Languages / C#

C# Entity Framework Class Generator for Data Layer

Rate me:
Please Sign up or sign in to vote.
4.96/5 (14 votes)
19 Jul 2017CPOL2 min read 34.8K   1.8K   31   12
Anytime you are developing a project using Entity Framework, you need to create a DataLayer class accessing each object within your model with different methods. This generator will do this stuff for you.

Introduction

I wrote this tool for myself creating data layer classes using the entity Framework based on template files. It connects to the SQL server and reads tables, views and their columns. On your click, it will generate basic data layer classes you can implement into your projects.

You can modifiy the code template files (included) to translate it to VB or add methods you miss.

Connect to SQL server

First, a connection to your SQL server need to estiblished.

Image 1

Code Generator

Now you enter some project related variables, choose a table, select the primary key column and sorting and click "Generate Class". Voila.

Image 2

Methods Generated

Inside the template files, there are some default methods created by generation. In case your table contains columns like "DELETED", "CREATED", UPDATED" (all of them are datetime) this generator will decide, which line needs to be generated.

Sample: You have a column "DELETED" (datetime) used to flag a record on deletion, this generator detect this.

The following methods will be generated for a table:

  • Create (record)
  • Update (record)
  • DeleteById (record)
  • DropById (record)
  • GetById (record)
  • GetList (list of records)
  • CleanMarkedAsDeleted (delete marked records for deletion)

The following methods will be generated for a view:

  • GetById (record)
  • GetList (list of records)

Add-On

Two additional options are available:

  • Generate the DatabaseException class, which is needed only once per project.
  • Generate a class for getting a SelectList for MVC projects. You can use this very easy in your ViewModel to fill combo boxes and lists with data.

Using the generated code in your destination project

As soon you implemented the generated class into your EF project, you can use this like this.
A sample based on the model object VEREIN:

Get a list of all VEREIN objects

C++
List<VEREIN> lst = EF.Verein.GetList();

Get one specific VEREIN object

Guid id = new Guid("7125A5EA-25EA-4C3F-A123-415506246359");
VEREIN verein = EF.Verein.GetByID(id);

Full context menu when using this class:

Image 3

Exception

The generated classes will need the DatabaseException class once, in which you fill your events on your need. Gererated exception class:

using System;
using System.Runtime.Serialization;

/// <summary>
/// Code generated 01.07.2017 09:50:23 by EFClassGenerator version 1.0.0.0
/// Template last modified 2017-06-23
/// </summary>

namespace TestProject
{
    [Serializable]
    public class DatabaseException : Exception
    {
        // Constructors
        public DatabaseException(string message)
            : base(message)
        {
        }
        public DatabaseException(string message, Exception innerException)
            : base(message)
        {
        }
        public DatabaseException(string format, params object[] args)
        : base(string.Format(format, args))
        {
        }

        // Ensure Exception is Serializable
        protected DatabaseException(SerializationInfo info, StreamingContext ctxt)
            : base(info, ctxt)
        {
        }
    }
}

SelectList

Only for MVC (ASP) projects but very helpfull filling combo boxes in views.
This generated code will return a MVC List<SelectListItem>filled with all VEREIN records (ID and Name) for a combo box.

using System;
using System.Collections.Generic;
using System.Linq;
using TestProject.Models;
using System.Web.Mvc;

/// <summary>
/// Code generated 01.07.2017 15:44:16 by EFClassGenerator version 1.0.0.0
/// Template last modified 2017-06-23
/// </summary>

namespace TestProject.EF
{
    class SelList_Verein
    {
        private const string exceptionMessage = "A database exception occurred";

        /// <summary>
        /// Returns a SelectListItem list of model objects out of database
        /// </summary>
        /// <returns> A list of SelectListItem - List of model object</returns>
        public static List<SelectListItem> GetList()
        {
            try
            {
                List<SelectListItem> sellist = new List<SelectListItem>();
                using (EFDataClassGeneratorEntities model = new EFDataClassGeneratorEntities())
                {
                    var list = model.VEREIN.OrderBy(w => w.VEREIN_NAME).ToList();
                    foreach (VEREIN item in list)
                    {
                        sellist.Add(new SelectListItem { Value = item.VEREIN_ID.ToString(), Text = item.VEREIN_NAME });
                    }
                    return sellist;
                }
            }
            catch (Exception ex)
            {
                throw new DatabaseException(exceptionMessage, ex);
            }
        }
    }
}

Source

I am not an enterprise developer and there is always something wrong with code from others than yourself. Take this sample as inspiration. Feel free to change the source like you want, edit the template files, do what you want.

But please don't criticize the way of coding.

Any other feedback is very welcome.

History

I will enhance this project by myself only. I guess further versions will not be posted here ny me.

2017/07/20

Updated the source and fixed some bugs

License

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


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

Comments and Discussions

 
GeneralMy vote of 5 Pin
Degryse Kris25-Jul-17 1:38
Degryse Kris25-Jul-17 1:38 
SuggestionSuggestions Pin
IsmailLunat24-Jul-17 18:51
IsmailLunat24-Jul-17 18:51 
GeneralRe: Suggestions Pin
malzbiertrinker7-Aug-17 19:22
malzbiertrinker7-Aug-17 19:22 
GeneralRe: Suggestions Pin
Member 122516178-Aug-17 4:42
Member 122516178-Aug-17 4:42 
QuestionWhat is the use case? Pin
Kangkan Goswami24-Jul-17 3:20
Kangkan Goswami24-Jul-17 3:20 
QuestionDAL Generator? Pin
Member 1225161723-Jul-17 23:47
Member 1225161723-Jul-17 23:47 
SuggestionYou may want to look at.... Pin
TheEdge221-Jul-17 18:55
TheEdge221-Jul-17 18:55 
QuestionWhat is the difference Pin
Mycroft Holmes20-Jul-17 20:20
professionalMycroft Holmes20-Jul-17 20:20 
AnswerRe: What is the difference Pin
malzbiertrinker7-Aug-17 19:16
malzbiertrinker7-Aug-17 19:16 
GeneralRe: What is the difference Pin
Member 122516178-Aug-17 4:18
Member 122516178-Aug-17 4:18 
Questiondon't be afraid PinPopular
tlang334-Jul-17 11:18
tlang334-Jul-17 11:18 
Praise5 of 5 Pin
NimoX3-Jul-17 4:37
NimoX3-Jul-17 4:37 

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.