Entity Framework – Using Visual Studio – Basic Application / Day 1

Background

In an earlier post, we spoke about how to generate an Entity Framework model through the command line.

 

Turnabout

And, our hope was to use a simple text editor along with command line tools such as msbuild and layer upon layer continue to build out our little application.

But, so little is publicly documented and shared about that approach and we quickly found in terms of straightforwardness, the plumbing available in Visual Studio will likely be best.

 

Visual Studio

Let go with Visual Studio.

 

Launch Visual Studio

Version – Microsoft Visual Studio Community 2015

New Project

Menu

We create a new project by clicking on the menu item ( File New/ Project ).

Template

GUI

Explanation
  1. Template
    • Visual C#\Windows\Console Application
  2. Name
    • Name :- lab001VS
  3. Location
    • C:\Personal\Blog\Microsoft\.net\entityFramework

Add

Add \ New Item..

Access the Solution Explorer, choose the Project, right click your selection and choose the Add Option

 

Add “ADO.Net Entity Data Model”

From the list of items, choose “ADO.Net Entity Data Model“.

 

Entity Data Model Wizard

The Entity Data Model Wizard appears….

Entity Data Model Wizard – Choose Model Contents

We are taking Database First approach, that is, we have a database defined, and will generate the entity code from the DB.

Please choose “EF Designer from database”

Entity Data Model Wizard – Choose Your Data Connection – Original

Here is the original state of the “Choose Your Data Connection” screen.

Please choose the “New Connection…” button.

 

Entity Data Model Wizard – Connection Properties

In the Connection Properties screen:

  1. Data Source :- Microsoft SQL Server (SqlClient)
  2. Server name :- .\v2014
  3. Logon to the Server :- SQL Server Authentication
  4. user name :- edmgen
  5. Password :- < enter password>
  6. Tick the “Save my password” checkbox
  7. Connect to a database :- Chose DBDiag
  8. Click the “Test Connection” button to validate the connection

 

Entity Data Model Wizard – Choose Your Database Objects And Settings

 

Connection Properties – Advanced Properties

Connection Properties – Advanced Properties – Before

 

Connection Properties – Test connection succeeded

 

Entity Data Model Wizard – Choose your Data Connection

Return to the “Choose your Data Connection” window.

 

Choices
  1. Connection info :-
    • [Server\instance].[database].[schema]
  2. Yes, include the sensitive data in the connection string
  3. Save connection settings in App.Config as …
    • DBDiagEntities

 

Entity Data Model Wizard – Choose your Version

  1. Which version of Entity Framework do you want to use?
    • Entity Framework 6.x
    • Entity Framework 5.0

 

Entity Data Model Wizard – Choose your Database Objects and Settings

Explanation
  1. Our SQL Account only has to the traceFlag table

 

 

 

Connection Properties – Advanced Properties

Connection Properties – Advanced Properties – Before

Connection Properties – Test connection succeeded

 

Entity Data Model Wizard – Choose your Version

  1. Which version of Entity Framework do you want to use?
    • Entity Framework 6.x
    • Entity Framework 5.0

 

 

Explanation

As this is a new test Application and we do not have a need to preserve existing code, we will go with the latest EF version, and that is Version 6.0.

 

Security Warning

There are a couple of security warnings that pop up and we click the OK to move on.

 

 

EDMX

The wizard does a bit of behind the scene work and publishes the model and the .Net class files

 

 

Source Code

With all that plumbing work out of the way, let us write a couple of elementary code that will invoke the method availed by EF entities.

 

Outline

  1. Display a simple UI that allows the user to List, Add, Edit, and Delete records
  2. List
    • List Trace Flags
  3. Add
    • Add a Trace Flag
  4. Edit
    • Edit a Trace Flag
  5. Remove
    • Remove a Trace Flag

 

Code

Browse


  public void browse()
        {

            //get all entities from entity traceflags
            //result should be captured in a variant variable tfQuery
            //ordering will likely be based on the DB table's primary key ( PK )
            var tfQuery = from tf in dbDE.traceFlags
                          select tf
                           ;

            //copy data into list object
            listTF = tfQuery.ToList();

            //Iterate list
            //Using foreach expose each list element in varTF
            foreach (var varTF in listTF)
            {

                //cast Var object to traceflag object
                objTF = (traceFlag)varTF;
                
                // prepare UI output
                strLog
                    = String.Format
                        (
                              FORMAT_BROWSE_DETAIL
                            , objTF.id
                            , objTF.description
                        );

                Console.WriteLine(strLog);

                // Output Line Break
                Console.WriteLine(CHAR_LINEBREAK);

            } //foreach

        } //browse

Add


 public void add()
        {
         
            Console.WriteLine("Get Trace Flag ID");
            strID = Console.ReadLine();

            if (strID == "")
            {
                return;
            }

            Console.WriteLine("Get Trace Flag Description");
            strDescription = Console.ReadLine();

            objTF = new traceFlag();

            objTF.id = Int32.Parse(strID);
            objTF.description = strDescription;
        
            dbDE.traceFlags.Add(objTF);

            dbDE.SaveChanges();

            objTF = null;


        } //add

Edit



  public void edit()
        {

            
            Console.WriteLine("Get Trace Flag ID");
            strID = Console.ReadLine();

            if (strID == "")
            {
                return;
            }

            iID = Int32.Parse(strID);

            var tfQuery = from tf in dbDE.traceFlags
                          where tf.id == iID
                          select tf
                ;

            objTF = new traceFlag();

            try
            {
                objTF = tfQuery.Single();
            }
            /*
                When ID Filtering is attempted, and matching record not found
                an exception, System.InvalidOperationException, is raised,
                catch and gracefully handle that exception
            */ 
            catch (System.InvalidOperationException exIOE)
            {
                strLog = String.Format
                    (
                        FORMAT_OPERATION_DELETE_FAILED
                        , "edit"
                        , strID
                        , exIOE.HResult
                        , exIOE.Message
                    );

                Console.WriteLine(strLog);

                //deallocated created object
                objTF = null;

                return;

            }


            //Get Trace Flag Description
            Console.WriteLine("Get Trace Flag Description");
            strDescription = Console.ReadLine();

            //If Description is empty, then exit
            if (strDescription == String.Empty)
            {

                //deallocated created object
                objTF = null;

                return;

            }

            //set Trace Flag Description
            objTF.description = strDescription;

            // save changes to db
            dbDE.SaveChanges();

            //deallocated created object
            objTF = null;



        } //edit


Remove



        public void remove()
        {

            Console.WriteLine("Get Trace Flag ID");
            strID = Console.ReadLine();

            if (strID == "")
            {
                return;
            }

            iID = Int32.Parse(strID);

            var tfQuery = from tf in dbDE.traceFlags
                          where tf.id == iID
                          select tf
                ;


            objTF = new traceFlag();

            try
            {
                objTF = tfQuery.Single();
            }
            /*
                When ID Filtering is attempted, and matching record not found
                an exception, System.InvalidOperationException, is raised,
                catch and gracefully handle that exception
            */
            catch (System.InvalidOperationException exIOE)
            {
                strLog = String.Format
                    (
                        FORMAT_OPERATION_DELETE_FAILED
                        , "deletion"
                        , strID
                        , exIOE.HResult
                        , exIOE.Message
                    );

                Console.WriteLine(strLog);

                //deallocated created object
                objTF = null;

                return;

            }

            //attach created object to trace flags entity
            dbDE.traceFlags.Attach(objTF);

            //mark the object for deletion
            dbDE.traceFlags.Remove(objTF);

            // save changes to db
            dbDE.SaveChanges();

            //deallocated created object
            objTF = null;

        } //remove



 

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s