Search This Blog

Wednesday, March 23, 2016

Entity Framework Code First

.NET offers many ways to access your database data being simply ADO.NET which let you connect to a database and then executing queries, to LINQ to SQL or Entity Framework.

Entity Framework (EF for short) is the biggest and maybe the more complex / complete officially supported way to access data with .NET. Yes there is other options like the open source project nhibernate or commercial solutions like LinqConnect.

Anyhow I would like to show here how simply it can be to create a mapping with EF.

Let's start from the beginning: let's add the NUGET package "EntityFramework".

Once this is done, let's create a context class:
using System.Data.Entity;
namespace TestEFCodeFirst
{
    public partial class DataContext : DbContext    {
        public DataContext()
            : base("name=DataContext")
        {
        }
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
        }
    }
}
This is where your data will be visible.

Now let's create a "Table" class:
namespace TestEFCodeFirst
{
    public class User
    {
        public int Id { getset; }
        public string Username { getset; }
        public string FirstName { getset; }
        public string LastName { getset; }
    }
}
Finally add this class to the context:
using System.Data.Entity;
namespace TestEFCodeFirst
{
    public partial class DataContext : DbContext    {
        public DataContext()
            : base("name=DataContext")
        {
        }
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
        }
        public virtual DbSet<User> Users { getset; }
    }
}
We need now just a database, and the application settings to point to it:
  <connectionStrings>    <add name="DataContext" connectionString="Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=Integrated Security=True;"  providerName="System.Data.SqlClient"/>  </connectionStrings>
And create the table:
CREATE TABLE Users(Id INT NOT NULL IDENTITY,Username VARCHAR(30) NOT NULL UNIQUE,FirstName VARCHAR(100),LastName VARCHAR(100));
Finally we can create the main class and test EF:
using System;
namespace TestEFCodeFirst
{
    class Program    {
        static void Main(string[] args)
        {
            using (var ctx = new DataContext())
            {
                // Cleanup the table (if we run it multiple times)                ctx.Users.RemoveRange(ctx.Users);
                // Insert 2 users                ctx.Users.Add(new User                {
                    Username = "Admin",
                    FirstName = "Administrator",
                    LastName = "The Guru"                });
                ctx.Users.Add(new User                {
                    Username = "User",
                    FirstName = "User",
                    LastName = "The simple guy"                });
                // Commit the changes to the database                ctx.SaveChanges();
                // Let's see what I have in the table                foreach (var i in ctx.Users)
                {
                    Console.WriteLine(i.Id + " " + i.Username);
                }
            }
            Console.ReadKey();
        }
    }
}
As you see, we did a DELETE, INSERT and SELECT all directly via code, using our classes and yet if you browse the database you will see that the data are actually stored in the table.

You can also query (with where), grab elements and modify them, and then save.

As developer it doesn't change if your data are in the database or would be in a list, it would work the same way. SQL injections are nothing to be worried about, and even better, your queries are (mostly) checked while compiling, which means forget typos into your SQL statements that you would discover only by testing.

You may wonder how the mapping works, well, there is many options letting you define the keys or the columns as you want, even renaming them from what you have on the database as what you have in the code.

With such minimalist work, being able to work on the database as you would with memory objects if for me something simply amazing. Don't get me wrong, for those which know what I'm talking about other tools than EF will do more or less the same work. Still it's great to have such tools available and even more so if they are part of the main framework.

No comments:

Post a Comment