Click here to Skip to main content
15,891,431 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.9K   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 
Hello,

Few thinks about your generator.

First of all - there are few generators for DAL layer. Some of them have a good integration with Studio. There are a reason to review those generators and figure out what is good and where is a problems. Most likely you will find that you not need a full application to generate a class, but require a new set of the templates to generate what you need.

There also are few problem on your the application.

Lorm logic. You have two form -
frmLogin
and
frmMain
open to generate a file. User have to close both to finish an application.

Configuration. You have few setting stored in config file. There is only ONE set of the settings. This mean that customer will have to manually overwrite those settings each time he decide to switch between sources.

Templates. You use a text-type templates with special markers (like '%...%') to locate place of substitution and a key for replacement value. Ok - this working. Problem with this is that very soon you will have to implement something which will allow you to iterate through elements of collection. For example - creating an Entity for a Table you will have throug list of the fields. In the way in which you make your implementation it would be too difficult (in some cases - impossible). Look on the T4 templates for solution.

Common. You allow to the customer manually manage a creation of single file in place where 3-5 files need to be created to have an implementation of things. There will be a lot of human's mistake. Specially, when require manually specify each configuration. Files which not organized (and you will have a problem to organize them into project regards a text-typed templates) also will give a lot of problem.

There also is few things which, I assume, you are not currently see.
One of them - there are not enough information in the database table definition to cover all requirements which you will face in near future. The simplest example - you have an 'Aaaa' table in the database and you want to have a 'Bbbb' in the output. More complicated - you have Table1 with PK_Field1 and you have Table2, which use (Field1, Field2) as foreign key to refer to Table1 (this couldn't be specified in the database).

I think that the mentioned problem will give you few possibilities to analyze what you trying to achieve and avoid some common mistakes.
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.