Friday, December 18, 2015

Intro to Entity Framework

When I was first starting with full-stack C#, my team was giving me some hints on ways to write effective, secure, reliable code, and understandably one of the first things that was mentioned was Entity Framework. I tried some Googling and reading on-hand textbooks, and unfortunately, I was unable to find any satisfactory blog posts or tutorials on the subject of EF. Most of them were outdated or way above a beginner user's head, so here we are: at a blog post that will serve as a very basic tutorial on some of EF's more useful features, skipping over a lot of the more powerful stuff in the name of clarity.

To start, Entity Framework is a Microsoft technology that is part of ADO.NET (the data access and control tier of .NET) that allows users to abstract away the idea of a database table into an object-oriented paradigm. Basically what it does is it takes a SQL Server table and makes it a C# object that you can operate on to change the table. It allows you to generate database tables from objects or vice versa and is very powerful. In this blog post, I'm going to outline how to make a simple EF object out of an existing SQL Server table.

Let's get into it! Before that though, please note that I use Visual Studio 2013 Ultimate and SQL Server Management Studio 2014, so somethings may look different if you're using different versions, but it's largely the same. Also, please note that I will be using Entity Framework version 6.1.3.

First, let's open up SQL Server Management Studio and create a new database by right-clicking the "Databases" folder in the Object Explorer and picking "New Database".






Name it whatever you'd like and click "Ok". I named mine EFTest. Next, right click the database you just made and click "New Query".




Great! Now let's create a table with some simple SQL code. We can create a table to model some basic user data, such as their user ID, their name, and email.


1
2
3
4
5
6
7
CREATE TABLE UsersTable
(
UserID int NOT NULL PRIMARY KEY,
FirstName varchar(255),
LastName varchar(255),
Email varchar(255)
);


Pretty easy! Press F5 to execute this statement, and the UsersTable will be created in the database we just made. You can see the contents of it using:


1
SELECT * FROM UsersTable;



It may take a second or two to recognize that the table was created, but if you execute the select statement it should work anyway, or you could right click the Tables folder and hit refresh and it will show up.

Next, open up Visual Studio and create a new console application. It should generate a new main method template. 

Now we need to add EF to our project. We can do that by right-clicking our project file in the Solution Explorer window and clicking "Manage NuGet packages". EF is usually the first one on the list, but if it isn't you can search for "Entity Framework" in the search bar and it should come up. Hit install, and then NuGet should do its thing, and we should be go to go! When you're done, it should look something like this:




Once you've done that, close NuGet and right-click your project file in the Solution Explorer. Select "Add" > "New Item". In the list of templates that comes up, find "ADO.NET Entity Data Model", click it, name the file something like "UsersDataModel.edmx" and click Add.




Click "Generate from database" and hit "Next".




In the next dialogue box, click the "New Connection" button towards the top-right, and then in the new window, pick "Microsoft SQL Server", and uncheck the box if you're afraid you want to change this setting in the future. Press continue.





In the next window, enter your database's server name, which can be found in the Object Explorer window of SQL Server Management Studio. Select or enter your database name below, and test your connection. It should pass, or something has gone terribly wrong. Make sure you're using the correct authentication method (Windows Auth or SQL Server Auth, depends on what you want. I'll use Windows Auth). You can fiddle around with the Advanced Settings if you'd like, but you don't need to.




Click "OK", then click "Next". You should be at the window that says "Choose Your Database Objects and Settings". Expand the Tables option and make sure that the UsersTable is checked. You can rename the model's namespace if you'd like, but I'll leave it default. Click "Finish".




That's all you need to do to get some basic EF generated code going! Before we start using the object, let's add an entry to the users table so we can actually see the results. Go back to SQL Server Management Studio, and write a query on the database we made that is:


1
INSERT INTO UsersTable VALUES (1, 'Jim', 'Calabro', 'jamesrcalabro@gmail.com');



This will make a user with an ID of 1, first name "Jim", last name "Calabro", and email "jamesrcalabro@gmail.com". Great! You can check that it worked by running the select statement again. It should show you the contents of the UsersTable in the bottom-center box.


1
SELECT * FROM UsersTable;


Let's open up the main method and start using it. It's best practice to encapsulate any EF Entities object in a using statement because the class we generated extends the DBContext class which implements IDisposable, so instead of needing to call the Dispose() method later in the code, our object will automatically be disposed at the end of the segment. We can check that everything worked by doing a Find call. Here is the entire program:



 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
namespace EntityFrameworkIntro
{
    using System;

    public class EntityFrameworkIntro
    {
        public static void Main(string[] args)
        {
            using (var dbContext = new EFTestEntities())
            {
                var user = dbContext.UsersTables.Find(1);
                Console.WriteLine(
                    String.Format("User {0} {1} has email address: {2}",
                    user.FirstName, user.LastName, user.Email));
            }

            Console.ReadLine();
        }
    }
}


Which should print:




in the console.

Awesome! So to do a quick review of what we did, we made a table in SQL Server Management Studio, made an ADO.NET object (EF object) to store data about that object, and we used that object to print some information on a row in a table containing user information. It's really powerful stuff, and we're just barely scratching the surface here. Try adding a stored procedure on your own, and try calling it using the dbContext object for instance. I hope that it has become clear that Entity Framework allows for safe, maintainable data access, because if you ever want to change something about the way the db, you just need to update the generated object. As long as you don't pull the carpet out from underneath what you've already written, you're golden. I hope that this has served as a readable intro to EF! Let me know if you have any questions or comments and as usual, thanks for reading!

No comments:

Post a Comment