Tuesday, March 14, 2017

An Introduction to Entity Framework for Absolute Beginners


This article introduces Entity Framework to absolute beginners. The article is meant for developers who are primarily using ADO.NET to write their data access layers. Many experienced developers will find this article very basic but since the article is written from the perspective of beginners, I've tried to keep things simple.


ADO.NET is a very strong framework for data access. ADO.NET has been around since many years and there are a lot of systems running over ADO.NET. Developers who are totally oblivious to the concept of ORMs will probably be asking "What is Entity Framework? What are the benefits of using it and is it an alternative to ADO.NET?"
Well, to answer the first question about what is Entity Framework, Entity Framework is an Object Relational Mapper (ORM). It basically generates business objects and entities according to the database tables and provides the mechanism for:
  1. Performing basic CRUD (Create, Read, Update, Delete) operations.
  2. Easily managing "1 to 1", "1 to many", and "many to many" relationships.
  3. Ability to have inheritance relationships between entities.
and to answer the second question, the benefits are:
  1. We can have all data access logic written in higher level languages.
  2. The conceptual model can be represented in a better way by using relationships among entities.
  3. The underlying data store can be replaced without much overhead since all data access logic is present at a higher level.
and finally, the last question that whether it is an alternative to ADO.NET, the answer would be "yes and no". Yes because the developer will not be writing ADO.NET methods and classes for performing data operations and no because this model is actually written on top of ADO.NET, meaning under this framework, we are still using ADO.NET. So let us look at the architecture of Entity Framework (diagram taken from MSDN):
Entity framework article image

Using the code

Let's try to understand the ease of use that Entity Framework provides by performing simple CRUD operations. Once we look at the code and how effortlessly and efficiently we can do these operations, the benefits of Entity Framework will become quite obvious.

Creating the database

Let's have a simple database with one table. Let's create a simple table for Contacts and we will perform CRUD operations on this table.
Entity framework article image

Adding the Entity Model to the Website

Once we have the database ready, we can add the entity model to our website. We can do this by adding an ADO.NET Entity Data Model to the website.

Entity framework article image
Once we select to add this data model to our website, we will have to select the approach we want to take for our Model's contents.
Entity framework article image
What this selection means is that we can either choose to generate the entity model from an existing database schema or we can design the entity model here and then later hook it up to the database. Since we already have the database ready, we will use the first option. Once the Model is generated, the Entity for each table is generated. The generated entity for our contact table is:
Entity framework article image
Also, the classes for performing database operations are also created. We just need to know how to use these classes to perform database operations.
Entity framework article image

Insert operation

Let us create a simple page to perform an insert operation.
Entity framework article image
Now once the user chooses to insert the values into the database, the actual data operation can be performed by using the AddObject method of the Model class entity collection. The following code snippet show how to perform the insert.
Contact con = new Contact();
con.fname = TextBox1.Text;
con.lname = TextBox2.Text;
con.phone = TextBox3.Text;

ContactsDb db = new ContactsDb();
This will insert the record into the table. You can notice the simplicity and efficiency of the code we wrote to perform the insertion.

Reading all the records

There are scenarios when we want to read all records. Let's say we are making a page that will display all the contact information in a single page.
Entity framework article image
We can retrieve the collection of Entities using the Model object to achieve this. The code snippet below will show how that can be done.
ContactsDb db = new ContactsDb();
Repeater1.DataSource = db.Contacts;

Selecting a specific record

If we want to select a specific record from the table, we can use the SingleOrDefault method on the Model's entities collection. Let's say we want the functionality of updating/deleting a record on a single page then we will first have to select the record based on the ID, then update/delete the selected record.
Entity framework article image
Selection of any particular record (Contact) based on ID can be done as:
int idToupdate = Convert.ToInt32(Request.QueryString["id"].ToString());
ContactsDb db = new ContactsDb();
Contact con = db.Contacts.SingleOrDefault(p => p.id == idToupdate);
Once this code is executed, the Contact object will contain the required values.

Updating the record

If we want to update a record, then a simple update operation can be performed as:
int idToupdate = Convert.ToInt32(Request.QueryString["id"].ToString());
ContactsDb db = new ContactsDb();
Contact con = db.Contacts.SingleOrDefault(p =>  p.id == idToupdate);

con.phone = TextBox1.Text;
Once this code executes, the value of phone number will be updated by a new value which is retrieved from TextBox1.

Deleting a record

If we want to delete a particular record then we can perform a delete operation by using the DeleteObjectfunction. The following code snippet demonstrates the same:
//delete this contact
int idToupdate = Convert.ToInt32(Request.QueryString["id"].ToString());
ContactsDb db = new ContactsDb();
Contact con = db.Contacts.SingleOrDefault(p => p.id == idToupdate);

Now that we have the basic CRUD operations performed on the database using the Entity Framework.

A note on Relationships and Lazy Loading

To understand the Entity Framework we need to understand some things like naming conventions, relationships between tables, and relationships between entities. Also, the concept of lazy loading once fully understood will give the power to the developer to use the Entity Framework efficiently.
Note: Since this is an introductory article on Entity Framework we have not discussed these things. Perhaps we will discuss them in a separate article.

Points of interest

Entity Framework has been in use for some time now. But there are many developers who are still getting started with Entity Framework. This article was meant as an overview of the Entity Framework. This should not be treated as a complete tutorial. Also, the code written is very simple and there is a lot of scope for optimization but since the idea here is to understand Entity Framework, I tried to keep the code simple and readable rather and optimal.
Note: To run the solution, please change the database path of ConnectionString in the web.config file.

Visual Studio 2017 RC review: a look at what’s new and improved

There’s no better time than now to start looking into new tools and technologies that are being released. AConnect(); 2016 Microsoft announced the availability of Visual Studio 2017 Release Candidate. This has given me a chance to install it for myself and take a deeper look at what is coming for this Visual Studio 2017 RC review. 
Note from Microsoft: As we prepare for release, we’re continuing to evolve the list of workloads. In particular, because the .NET Core, Xamarin, Python, and Data Science workloads have not yet reached RC-quality, we have marked them as “Preview” quality. These three workloads should not be relied on in a production environment at this stage.
In this article, I’ll take a look at what is new and improved with Visual Studio coming into 2017, so you can get a feel of what is coming up before you try it out for yourself. 

First impressions

The new installation process
The first thing I noticed when installing Visual Studio 2017 RC was the new installer. In Microsoft’s release notes they said that they built this new installer for a couple of reasons:
  1. To reduce the minimum footprint of Visual Studio
  2. Install more quickly with less system impact, and uninstall cleanly
  3. Make it easier for you to select and install just the features you need
After downloading the installer from Microsoft’s website and running it, you are greeted with the usual T&Cs and privacy policy. After accepting this you then proceed to something new, the component selection step.
This is an awesome new part of the installation process. If you’re just after a basic install you can skip this step, this will bring the total size of the install to 740MB! This is much better than the 8GB needed for a basic install of VS 2015 and will still support over 20 different languages, source control, and even IntelliSense.
Most users will want to install more. You can choose to add ‘Workloads’ that are grouped frameworks, languages, and platforms: 
Or if you know exactly what you want, you can then open the ‘Individual components’ tab and manually select what you need:
you can choose to add ‘Workloads’ that are grouped frameworks and individual components
It’s great to see support for mobile and game development workloads added to the installer, along with other toolsets for Visual Studio extension and Linux development. These workloads have support for Xamarin, Cordova, DirectX, Unreal and Cocos2D:
mobile development was an important testing feature for this Visual Studio 2017 RC reviewother-toolsets
For my install, I only selected the Web Development and Node.js workloads as it was all I needed. This brought the total of my install to 5.02GB.
First time on Visual Studio 2017 RC
When I first opened VS 2017 I felt right at home. Coming from VS 2015 myself I was interested to see if there were any changes to the UI. As I logged into my Visual Studio account, before it even started, it loaded up all my preferences. This gave me a seamless transition between the 2015 and 2017 version.

What’s new

There are many updates coming in the new release of Visual Studio. Unfortunately, I won’t be able to cover them all in this Visual Studio 2017 RC review, but I’ll cover a selection of updates. Please take a look at the release notes if you want to know which other updates are coming in 2017.
Here are the ones that stood out for me:
Improved performance
Enhancements to the navigation, IntelliSense, refactoring, code fixes and debugging saves you time and effort on every-day tasks regardless of language or platform:
  • Visual Studio has been optimized to reduce startup time and solution load time. The very first launch of Visual Studio is at least 50% faster
  • Visual Studio will now monitor extension performance that impacts startup, solution load, or editing. You will receive alerts about poorly performing extensions via the Notification bar in the IDE
  • ‘Reload all projects’ has been replaced with ‘Reload solution’ to support better performance of switching branches external to Visual Studio
‘Run to click’ debugging
With the new ‘Run to click’ debugging feature you no longer need to set temporary breakpoints or perform several steps to execute your code and stop on the line you want. While stopped in a break state, you should see the ‘Run to click’ icon appear next to the line of code that your mouse is hovered over. Simply click the icon while debugging and your code should run to that line:
   Run to click debugging is also a great feature we chose to highlight in this Visual Studio 2017 RC review
Using the ‘Run to click’ feature you can also view information about how fast it took for the block to execute, process memory and CPU usage. Using this you can drill down until you find out exactly where your issues are.
‘Go to All’ feature
You can now navigate through your whole project using the ‘Go to All…’ search that is replacing the ‘Navigate to…’ one. This feature can be found under Edit > Go to > Go to All… or you can use the shortcut ctrl + , or ctrl + t.  
I found this search to be extremely powerful especially in bigger applications. After you enter your search query, it will show a dropdown of all the occurrences found. The powerful search looks not only at file names but also within each file and file path. As you move through the dropdown, Visual Studio will open a peek-preview in the temporary dock view to help you find what you’re looking for:
Go to all search is a powerful feature of the new Visual Studio RC

‘Find all references’ feature

Updates to the ‘Find all references’ output has now made it much easier to sift your way through the results. The search output now has syntax colouring and splits all the information into their respective columns. These columns can be customized so you only see what you want in the output. Another great addition is that they added ‘Peek preview’ to the output, and hovering your mouse over the reference will show you the block of code that it was found in.
Looking at this comparison of VS 2017 to VS 2015 you can easily see the change in readability:
Visual Studio 2017:
 A comparison between 2015 and 2017 in this Visual Studio 2017 RC review
Visual Studio 2015:
A comparison between 2015 and 2017 in this Visual Studio 2017 RC review
Smarter auto-complete
Adjustments to the IntelliSense autocomplete means no more scrolling through a massive list of possible recommendations. Instead it will jump straight to the most likely option. It can now also tell the difference between capital case and lower case to make using shorthand autocomplete searches even shorter.
The new exception helper
The new version of Visual Studio also includes a new simplified, non-modal, exception helper. This is to help make finding out why exceptions are causing issues in your code easier. You can use this helper to easily view your exception information at glance with instant access to inner exceptions.
If you’re diagnosing a NullReference exception the helper will point out exactly what was null so you can quickly continue investigating the issue.
Using the new exception helper, you can now exclude breaking on exception types thrown from specific modules. To do this, simply click a checkbox to add a condition while stopped at the thrown exception:
'unhandled exception' is one of the benefits of Visual Studio RC 2017
Click here to read more about the benefits of the new exception helper.

Visual Studio 2017 RC review: final thoughts

I really enjoyed my experience with the new Visual Studio. If you use this as an IDE I would highly recommend trying it out for yourself to explore the new updates.
Do you have any thoughts on the new Visual Studio? Let us know in the comments below!

Related articles

Raygun Crash Reporting and Visual Studio Online work together for a better error management process. Take a free 14 day trial here, or book a short demo with our team.

Popular Posts