Caution

This documentation is for EF7 onwards. For EF6.x and earlier release see http://msdn.com/data/ef.

Note

This article uses EF 7.0.0-rc1 which is the latest pre-release available on NuGet.org. You can find nightly builds of the EF7 code base hosted on https://www.myget.org/F/aspnetvnext/ but we do not maintain up-to-date documentation for nightly builds.

Console Application to Existing Database (Database First)

In this walkthrough, you will build a console application that performs basic data access against a Microsoft SQL Server database using Entity Framework. You will use reverse engineering to create an Entity Framework model based on an existing database.

In this article:

Tip

You can view this article’s sample on GitHub.

Prerequisites

The following prerequisites are needed to complete this walkthrough:

Latest version of NuGet Package Manager

Installing EF7 requires an up-to-date version of NuGet Package Manager. You can install the latest version from Visual Studio Gallery. Make sure you restart Visual Studio after installing the update.

Blogging database

This tutorial uses a Blogging database on your LocalDb instance as the existing database.

Note

If you have already created the Blogging database as part of another tutorial, you can skip these steps.

  • Tools ‣ Connect to Database...
  • Select Microsoft SQL Server and click Continue
  • Enter (localdb)\mssqllocaldb as the Server Name
  • Enter master as the Database Name
  • The master database is now displayed under Data Connections in Server Explorer
  • Right-click on the database in Server Explorer and select New Query
  • Copy the script, listed below, into the query editor
  • Right-click on the query editor and select Execute
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
CREATE DATABASE [Blogging]
GO

USE [Blogging]
GO

CREATE TABLE [Blog] (
    [BlogId] int NOT NULL IDENTITY,
    [Url] nvarchar(max) NOT NULL,
    CONSTRAINT [PK_Blog] PRIMARY KEY ([BlogId])
);
GO

CREATE TABLE [Post] (
    [PostId] int NOT NULL IDENTITY,
    [BlogId] int NOT NULL,
    [Content] nvarchar(max),
    [Title] nvarchar(max),
    CONSTRAINT [PK_Post] PRIMARY KEY ([PostId]),
    CONSTRAINT [FK_Post_Blog_BlogId] FOREIGN KEY ([BlogId]) REFERENCES [Blog] ([BlogId]) ON DELETE CASCADE
);
GO

INSERT INTO [Blog] (Url) VALUES 
('http://blogs.msdn.com/dotnet'), 
('http://blogs.msdn.com/webdev'), 
('http://blogs.msdn.com/visualstudio')
GO

Create a new project

  • Open Visual Studio (this walkthrough uses 2015 but you can use any version from 2013 onwards)
  • File ‣ New ‣ Project...
  • From the left menu select Templates ‣ Visual C# ‣ Windows
  • Select the Console Application project template
  • Ensure you are targeting .NET Framework 4.5.1 or later
  • Give the project a name and click OK

Install Entity Framework

To use EF7 you install the package for the database provider(s) you want to target. This walkthrough uses SQL Server. For a list of available providers see Database Providers.

  • Tools ‣ NuGet Package Manager ‣ Package Manager Console
  • Run Install-Package EntityFramework.MicrosoftSqlServer –Pre

To enable reverse engineering from an existing database we need to install a couple of other packages too.

  • Run Install-Package EntityFramework.Commands –Pre
  • Run Install-Package EntityFramework.MicrosoftSqlServer.Design –Pre

Reverse engineer your model

Now it’s time to create the EF model based on your existing database.

  • Tools –> NuGet Package Manager –> Package Manager Console
  • Run the following command to create a model from the existing database
Scaffold-DbContext -provider EntityFramework.MicrosoftSqlServer -connection "Server=(localdb)\mssqllocaldb;Database=Blogging;Trusted_Connection=True;"

The reverse engineer process created entity classes and a derived context based on the schema of the existing database.

Entity Classes

The entity classes are simple C# objects that represent the data you will be querying and saving.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
using System;
using System.Collections.Generic;

namespace EFGetStarted.ConsoleApp.ExistingDb
{
    public partial class Blog
    {
        public Blog()
        {
            Post = new HashSet<Post>();
        }

        public int BlogId { get; set; }
        public string Url { get; set; }

        public virtual ICollection<Post> Post { get; set; }
    }
}

Derived Context

The context represents a session with the database and allows you to query and save instances of the entity classes.

Note

Notice the OnConfiguring method (new in EF7) that is used to specify the provider to use and, optionally, other configuration too.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
using Microsoft.Data.Entity;
using Microsoft.Data.Entity.Metadata;

namespace EFGetStarted.ConsoleApp.ExistingDb
{
    public partial class BloggingContext : DbContext
    {
        protected override void OnConfiguring(DbContextOptionsBuilder options)
        {
            options.UseSqlServer(@"Server=(localdb)\mssqllocaldb;Database=Blogging;Trusted_Connection=True;");
        }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity<Blog>(entity =>
            {
                entity.Property(e => e.Url).IsRequired();
            });

            modelBuilder.Entity<Post>(entity =>
            {
                entity.HasOne(d => d.Blog).WithMany(p => p.Post).HasForeignKey(d => d.BlogId);
            });
        }

        public virtual DbSet<Blog> Blog { get; set; }
        public virtual DbSet<Post> Post { get; set; }
    }
}

Use your model

You can now use your model to perform data access.

  • Open Program.cs
  • Replace the contents of the file with the following code
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
using System;

namespace EFGetStarted.ConsoleApp.ExistingDb
{
    class Program
    {
        static void Main(string[] args)
        {
            using (var db = new BloggingContext())
            {
                db.Blog.Add(new Blog { Url = "http://blogs.msdn.com/adonet" });
                var count = db.SaveChanges();
                Console.WriteLine("{0} records saved to database", count);

                Console.WriteLine();
                Console.WriteLine("All blogs in database:");
                foreach (var blog in db.Blog)
                {
                    Console.WriteLine(" - {0}", blog.Url);
                }
            }
        }
    }
}
  • Debug ‣ Start Without Debugging

You will see that one blog is saved to the database and then the details of all blogs are printed to the console.

../../_images/output-existing-db.png