Sunteți pe pagina 1din 49

Entity Framework Documentation

Release 7.0.0

Microsoft

September 02, 2015

Contents

Getting Started
1.1 Getting Started on Full .NET (Console, WinForms, WPF, etc.)
1.2 Getting Started on ASP.NET 5 . . . . . . . . . . . . . . . . .
1.3 Getting Started on Universal Windows Platform . . . . . . .
1.4 Getting Started on OSX . . . . . . . . . . . . . . . . . . . .
1.5 Getting Started on Linux . . . . . . . . . . . . . . . . . . . .

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

.
.
.
.
.

3
3
6
14
20
26

Database Providers
2.1 EntityFramework.SqlServer . . . . . .
2.2 EntityFramework.SQLite . . . . . . .
2.3 EntityFramework.InMemory . . . . . .
2.4 EntityFramework.SqlServerCompact40
2.5 EntityFramework.SqlServerCompact35
2.6 EntityFramework.Npgsql . . . . . . .

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

33
33
33
34
34
34
34

Modeling
3.1
Default Conventions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
3.2 Configuring Your Model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

35
35
35

Contribute

45

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

ii

Entity Framework Documentation, Release 7.0.0

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

Note: This documentation is a work in progress. Topics marked with a are placeholders that have not been written
yet. You can track the status of these topics through our public documentation issue tracker. Learn how you can
contribute on GitHub.
Caution: This documentation is for EF7 onwards. For EF6.x and earlier release see http://msdn.com/data/ef.

Contents

Entity Framework Documentation, Release 7.0.0

Contents

CHAPTER 1

Getting Started

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

1.1 Getting Started on Full .NET (Console, WinForms, WPF, etc.)


In this walkthrough, you will build a console application that performs basic data access using Entity Framework.
In this article:
Ensure NuGet 2.8.6 or later
Create a new project
Install Entity Framework
Create your model
Create your database
Use your model
View this articles samples on GitHub.
Note: This walkthrough uses EF 7.0.0-beta7 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/api/v2/ but the code
base is rapidly changing and we do not maintain up-to-date documentation for getting started.

1.1.1 Ensure NuGet 2.8.6 or later


Installing EF7 requires NuGet 2.8.6 (or higher). Make sure you restart Visual Studio after installing the update.
Visual Studio 2015 - No updates needed, a compatible version of NuGet is included.
Visual Studio 2013 - Install the latest NuGet for VS2013.
Visual Studio 2012 - Install the latest NuGet for VS2012.
Note: NuGet version numbers can be confusing, while the required release is branded 2.8.6 the product version of
the extension is 2.8.60610.xxx.

Entity Framework Documentation, Release 7.0.0

1.1.2 Create a new project


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

1.1.3 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.SqlServer -Pre
Later in this walkthrough we will also be using some Entity Framework commands to maintain the database. So we
will install the commands package as well.
Run Install-Package EntityFramework.Commands -Pre

1.1.4 Create your model


Now its time to define a context and entity classes that make up your model.
Project Add Class...
Enter Model.cs as the name and click OK
Replace the contents of the file with the following code
Note: Notice the OnConfiguring method (new in EF7) that is used to specify the provider to use and, optionally,
other configuration too.
1
2

using Microsoft.Data.Entity;
using System.Collections.Generic;

3
4
5
6
7
8
9

namespace EFGetStarted.ConsoleApp
{
public class BloggingContext : DbContext
{
public DbSet<Blog> Blogs { get; set; }
public DbSet<Post> Posts { get; set; }

10

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)


{
// Visual Studio 2015 | Use the LocalDb 12 instance created by Visual Studio
optionsBuilder.UseSqlServer(@"Server=(localdb)\mssqllocaldb;Database=EFGetStarted.Console

11
12
13
14
15

// Visual Studio 2013 | Use the LocalDb 11 instance created by Visual Studio
// optionsBuilder.UseSqlServer(@"Server=(localdb)\v11.0;Database=EFGetStarted.ConsoleApp;

16
17
18

Chapter 1. Getting Started

Entity Framework Documentation, Release 7.0.0

// Visual Studio 2012 | Use the SQL Express instance created by Visual Studio
// optionsBuilder.UseSqlServer(@"Server=.\SQLEXPRESS;Database=EFGetStarted.ConsoleApp;Tru

19
20

21
22

protected override void OnModelCreating(ModelBuilder modelBuilder)


{
// Make Blog.Url required
modelBuilder.Entity<Blog>()
.Property(b => b.Url)
.Required();
}

23
24
25
26
27
28
29

30
31

public class Blog


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

32
33
34
35
36

public List<Post> Posts { get; set; }

37

38
39

public class Post


{
public int PostId { get; set; }
public string Title { get; set; }
public string Content { get; set; }

40
41
42
43
44
45

public int BlogId { get; set; }


public Blog Blog { get; set; }

46
47

48
49

1.1.5 Create your database


Now that you have a model, you can use migrations to create a database for you.
Tools > NuGet Package Manager > Package Manager Console
Run Add-Migration MyFirstMigration to scaffold a migration to create the initial set of tables for
your model.
Run Update-Database to apply the new migration to the database. Because your database doesnt exist yet,
it will be created for you before the migration is applied.
Tip: If you make future changes to your model, you can use the Add-Migration command to scaffold a new
migration to apply the corresponding changes to the database. Once you have checked the scaffolded code (and made
any required changes), you can use the Update-Database command to apply the changes to the database.

1.1.6 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.1. Getting Started on Full .NET (Console, WinForms, WPF, etc.)

Entity Framework Documentation, Release 7.0.0

using System;

2
3
4
5
6
7
8
9
10
11
12
13

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

14

Console.WriteLine();
Console.WriteLine("All blogs in database:");
foreach (var blog in db.Blogs)
{
Console.WriteLine(" - {0}", blog.Url);
}

15
16
17
18
19
20

21

22

23
24

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.

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

1.2 Getting Started on ASP.NET 5


In this walkthrough, you will build an ASP.NET 5 MVC application that performs basic data access using Entity
Framework.
In this article:
Create a new project
Install Entity Framework
Create your model
Register your context with dependency injection
6

Chapter 1. Getting Started

Entity Framework Documentation, Release 7.0.0

Create your database


Create a controller
Create views
Run the application
View this articles samples on GitHub.
Note: This walkthrough uses EF 7.0.0-beta7 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/api/v2/ but the code
base is rapidly changing and we do not maintain up-to-date documentation for getting started.

1.2.1 Prerequisites
The following items are required to complete this walkthrough:
Visual Studio 2015

1.2.2 Create a new project


Open Visual Studio 2015
File New Project...
From the left menu select Templates Visual C# Web
Select the ASP.NET Web Application project template
Ensure you are targeting .NET 4.5.1 or later
Enter EFGetStarted.AspNet5 as the name and click OK
When the New ASP.NET Project dialog appears:
Under ASP.NET 5 Preview Templates select Web Application
Ensure that Authentication is set to No Authentication
Click OK
Caution: If you use Individual User Accounts instead of None for Authentication then an Entity Framework
model will be added to your project in Models\IdentityModel.cs.
Using the techniques you will learn in this walkthrough, you can chose to add a second model, or extend this
existing model to contain your entity classes.

1.2.3 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.SqlServer -Pre

1.2. Getting Started on ASP.NET 5

Entity Framework Documentation, Release 7.0.0

Note: In ASP.NET 5 projects the Install-Package will complete quickly and the package installation will
occur in the background. You will see (Restoring...) appear next to References in Solution Explorer while the install
occurs.
Later in this walkthrough we will also be using some Entity Framework commands to maintain the database. So we
will install the commands package as well.
Run Install-Package EntityFramework.Commands -Pre
Open project.json
Locate the commands section and add the ef command as shown below
"commands": {
"web": "Microsoft.AspNet.Hosting --config hosting.ini",
"ef": "EntityFramework.Commands"

1
2
3

1.2.4 Create your model


Now its time to define a context and entity classes that make up your model.
Right-click on the project in Solution Explorer and select Add New Folder
Enter Models as the name of the folder
Right-click on the Models folder and select Add New Item...
From the left menu select Installed Server-side
Select the Class item template
Enter BloggingModel.cs as the name and click OK
Replace the contents of the file with the following code
1
2

using Microsoft.Data.Entity;
using System.Collections.Generic;

3
4
5
6
7
8
9

namespace EFGetStarted.AspNet5.Models
{
public class BloggingContext : DbContext
{
public DbSet<Blog> Blogs { get; set; }
public DbSet<Post> Posts { get; set; }

10

protected override void OnModelCreating(ModelBuilder modelBuilder)


{
// Make Blog.Url required
modelBuilder.Entity<Blog>()
.Property(b => b.Url)
.Required();
}

11
12
13
14
15
16
17

18
19

public class Blog


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

20
21
22
23
24

Chapter 1. Getting Started

Entity Framework Documentation, Release 7.0.0

public List<Post> Posts { get; set; }

25

26
27

public class Post


{
public int PostId { get; set; }
public string Title { get; set; }
public string Content { get; set; }

28
29
30
31
32
33

public int BlogId { get; set; }


public Blog Blog { get; set; }

34
35

36
37

1.2.5 Register your context with dependency injection


The concept of dependency injection is central to ASP.NET 5. Services (such as our BloggingContext) are
registered with dependency injection during application startup. Components that require these services (such as our
MVC controllers) are then provided these services via constructor parameters or properties.
Tip: For more information on dependency injection see the Dependency Injection article on the ASP.NET site.
In order for our MVC controllers to make use of BloggingContext we are going to register it as a service.
Open Startup.cs
Add the following using statements at the start of the file
1
2

using Microsoft.Data.Entity;
using EFGetStarted.AspNet5.Models;

Now we can use the AddDbContext method to register it as a service.


Locate the ConfigureServices method
Add the lines that are highlighted in the following code
1
2
3
4

// This method gets called by the runtime.


public void ConfigureServices(IServiceCollection services)
{
var connection = @"Server=(localdb)\mssqllocaldb;Database=EFGetStarted.AspNet5;Trusted_Co

5
6
7
8

services.AddEntityFramework()
.AddSqlServer()
.AddDbContext<BloggingContext>(options => options.UseSqlServer(connection));

9
10

// Add MVC services to the services container.

1.2.6 Create your database


Caution: The migrations experience in ASP.NET 5 is still a work-in-progress. The following steps are overly
complex and will be simplified by the time we reach a stable release.
Now that you have a model, you can use migrations to create a database for you.
Open a command prompt (Windows Key + R, type cmd, click OK)

1.2. Getting Started on ASP.NET 5

Entity Framework Documentation, Release 7.0.0

Use the cd command to navigate to the project directory


Run dnvm use 1.0.0-beta7
Run dnx ef migrations add MyFirstMigration to scaffold a migration to create the initial
set of tables for your model.
Run dnx ef database update to apply the new migration to the database. Because your database
doesnt exist yet, it will be created for you before the migration is applied.
Tip: If you make future changes to your model, you can use the dnx ef migrations add command to scaffold
a new migration to apply the corresponding changes to the database. Once you have checked the scaffolded code
(and made any required changes), you can use the dnx database update command to apply the changes to the
database.

1.2.7 Create a controller


Next, well add an MVC controller that will use EF to query and save data.
Right-click on the Controllers folder in Solution Explorer and select Add New Item...
From the left menu select Installed Server-side
Select the Class item template
Enter BlogsController.cs as the name and click OK
Replace the contents of the file with the following code
1
2
3

using EFGetStarted.AspNet5.Models;
using Microsoft.AspNet.Mvc;
using System.Linq;

4
5
6
7
8
9

namespace EFGetStarted.AspNet5.Controllers
{
public class BlogsController : Controller
{
private BloggingContext _context;

10

public BlogsController(BloggingContext context)


{
_context = context;
}

11
12
13
14
15

public IActionResult Index()


{
return View(_context.Blogs.ToList());
}

16
17
18
19
20

public IActionResult Create()


{
return View();
}

21
22
23
24
25

[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult Create(Blog blog)
{
if (ModelState.IsValid)

26
27
28
29
30

10

Chapter 1. Getting Started

Entity Framework Documentation, Release 7.0.0

31

_context.Blogs.Add(blog);
_context.SaveChanges();
return RedirectToAction("Index");

32
33
34

35
36

return View(blog);

37

38
39

40
41

Youll notice that the controller takes a BlogContext as a constructor parameter. ASP.NET dependency injection
will take care of passing an instance of BlogContext into your controller.
The controller contains an Index action, which displays all blogs in the database, and a Create action, which inserts
a new blogs into the database.

1.2.8 Create views


Now that we have a controller its time to add the views that will make up the user interface.
Well start with the view for our Index action, that displays all blogs.
Right-click on the Views folder in Solution Explorer and select Add New Folder
Enter Blogs as the name of the folder
Right-click on the Blogs folder and select Add New Item...
From the left menu select Installed Server-side
Select the MVC View Page item template
Enter Index.cshtml as the name and click OK
Replace the contents of the file with the following code
1

@model IEnumerable<EFGetStarted.AspNet5.Models.Blog>

2
3

@{
ViewBag.Title = "Blogs";

4
5

6
7

<h2>Blogs</h2>

8
9
10
11

<p>
@Html.ActionLink("Create New", "Create")
</p>

12
13
14
15
16
17

<table class="table">
<tr>
<th>Id</th>
<th>Url</th>
</tr>

18
19
20
21
22

@foreach (var item in Model)


{
<tr>
<td>

1.2. Getting Started on ASP.NET 5

11

Entity Framework Documentation, Release 7.0.0

@Html.DisplayFor(modelItem => item.BlogId)


</td>
<td>
@Html.DisplayFor(modelItem => item.Url)
</td>
</tr>

23
24
25
26
27
28
29
30

}
</table>

Well also add a view for the Create action, which allows the user to enter details for a new blog.
Right-click on the Blogs folder and select Add New Item...
From the left menu select Installed ASP.NET 5
Select the MVC View Page item template
Enter Create.cshtml as the name and click OK
Replace the contents of the file with the following code
1

@model EFGetStarted.AspNet5.Models.Blog

2
3

@{
ViewBag.Title = "New Blog";

4
5

6
7

<h2>New Blog</h2>

8
9
10
11

@using (Html.BeginForm())
{
@Html.AntiForgeryToken()

12

<div class="form-horizontal">
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<div class="form-group">
@Html.LabelFor(model => model.Url, htmlAttributes: new { @class = "control-label col-md-2
<div class="col-md-10">
@Html.EditorFor(model => model.Url, new { htmlAttributes = new { @class = "form-contr
@Html.ValidationMessageFor(model => model.Url, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>

13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28

1.2.9 Run the application


You can now run the application to see it in action.
Debug Start Without Debugging
The application will build and open in a web browser
Navigate to /Blogs

12

Chapter 1. Getting Started

Entity Framework Documentation, Release 7.0.0

Click Create New


Enter a Url for the new blog and click Create

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

1.2. Getting Started on ASP.NET 5

13

Entity Framework Documentation, Release 7.0.0

1.3 Getting Started on Universal Windows Platform


In this walkthrough, you will build a Universal Windows Platform (UWP) application that performs basic data access
against a local SQLite database using Entity Framework.
Caution: Pre-releases of EF7 can be used on UWP but there are a number of known issues that you need to
workaround. Look out for caution boxes (such as this one) that provide details of required workarounds.
Well be working to address these issues in upcoming releases. In fact, some of them are already fixed in our
working code base.
In this article:
Prerequisites
Create a new project
Install Entity Framework
Create your model
Create your database
Use your model
View this articles samples on GitHub.
Caution: This walkthrough uses EF 7.0.0-beta6. Version 7.0.0-beta7 is available on NuGet.org, but some
issues prevent it from being installed in a UWP application.
You can find nightly builds of the EF7 code base hosted on https://www.myget.org/F/aspnetvnext/api/v2/ but the
code base is rapidly changing and we do not maintain up-to-date documentation for getting started.

1.3.1 Prerequisites
The following items are required to complete this walkthrough:
Windows 10 RTM
Visual Studio 2015 RTM with Window 10 Developer Tools
Tip: If you already have Visual Studio 2015 RTM installed without the Windows 10 Developer Tools, you can add
these tools to your existing Visual Studio installation. You can run the installer, or open Programs and Features
from Control Panel, select Visual Studio and click Change. Then in setup, click Modify and select the Tools for
Universal Windows Apps.

1.3.2 Create a new project


Open Visual Studio 2015
File New Project...
From the left menu select Templates Visual C# Windows Universal
Select the Blank App (Universal Windows) project template
Give the project a name and click OK

14

Chapter 1. Getting Started

Entity Framework Documentation, Release 7.0.0

1.3.3 Install Entity Framework


To use EF7 you install the package for the database provider(s) you want to target. This walkthrough uses SQLite. For
a list of available providers see Database Providers.
Tools NuGet Package Manager Package Manager Console
Run Install-Package EntityFramework.SQLite -Version 7.0.0-beta6
Later in this walkthrough we will also be using some Entity Framework commands to maintain the database. So we
will install the commands package as well.
Run Install-Package EntityFramework.Commands -Version 7.0.0-beta6
Run Install-Package Microsoft.CodeAnalysis.CSharp -Version 1.0.0
Caution: Note that the commands explicitly install EF 7.0.0-beta6. Version 7.0.0-beta7 is available on
NuGet.org, but some issues prevent it from being installed in a UWP application.
Needing to install the Microsoft.CodeAnalysis.CSharp package is a workaround for an issue in Beta 6. This will
not be required in later releases.

1.3.4 Create your model


Now its time to define a context and entity classes that make up your model.
Project Add Class...
Enter Model.cs as the name and click OK
Replace the contents of the file with the following code
Caution: The try/catch code to set databaseFilePath is a temporary workaround to enable migrations to be added at design time. When the application runs, databaseFilePath will always be under
ApplicationData.Current.LocalFolder.Path. However, that API can not be called when migrations creates the context at design time in Visual Studio. The database is never accessed when adding migrations,
so we just return a relative file path that will never be used.

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

using
using
using
using
using

Microsoft.Data.Entity;
System;
System.Collections.Generic;
System.IO;
Windows.Storage;

6
7
8
9
10
11
12

namespace EFGetStarted.UWP
{
public class BloggingContext : DbContext
{
public DbSet<Blog> Blogs { get; set; }
public DbSet<Post> Posts { get; set; }

13
14
15
16

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)


{
string databaseFilePath = "Blogging2.db";

1.3. Getting Started on Universal Windows Platform

15

Entity Framework Documentation, Release 7.0.0

try
{

17
18

databaseFilePath = Path.Combine(ApplicationData.Current.LocalFolder.Path, databaseFil


}
catch (InvalidOperationException)
{ }

19
20
21
22
23

optionsBuilder.UseSqlite($"Data source={databaseFilePath}");

24

25
26

protected override void OnModelCreating(ModelBuilder modelBuilder)


{
// Make Blog.Url required
modelBuilder.Entity<Blog>()
.Property(b => b.Url)
.Required();
}

27
28
29
30
31
32
33

34
35

public class Blog


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

36
37
38
39
40

public List<Post> Posts { get; set; }

41

42
43

public class Post


{
public int PostId { get; set; }
public string Title { get; set; }
public string Content { get; set; }

44
45
46
47
48
49

public int BlogId { get; set; }


public Blog Blog { get; set; }

50
51

52
53

1.3.5 Create your database


Now that you have a model, you can use migrations to create a database for you.
Build -> Build Solution
Tools > NuGet Package Manager > Package Manager Console
Run Add-Migration MyFirstMigration to scaffold a migration to create the initial set of tables for
your model.
Caution: Notice that you need to manually build the solution before running the Add-Migration command.
The command does invoke the build operation on the project, but we are currently investigating why this does not
result in the correct assemblies being outputted.

16

Chapter 1. Getting Started

Entity Framework Documentation, Release 7.0.0

Caution: Due to a bug in the migration scaffolder in Beta6 you will need to manually edit the generated migration.
Remove (or comment out) the two calls to .Annotation("Sqlite:Autoincrement", true) as highlighted in the following code listing
public override void Up(MigrationBuilder migration)
{
migration.CreateTable(
name: "Blog",
columns: table => new
{
BlogId = table.Column(type: "INTEGER", nullable: false),
//.Annotation("Sqlite:Autoincrement", "true"), // <Url = table.Column(type: "TEXT", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Blog", x => x.BlogId);
});
migration.CreateTable(
name: "Post",
columns: table => new
{
PostId = table.Column(type: "INTEGER", nullable: false),
//.Annotation("Sqlite:Autoincrement", "true"), // <BlogId = table.Column(type: "INTEGER", nullable: false),
Content = table.Column(type: "TEXT", nullable: true),

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22

// <- Add this comma


Remove or comment this

// <- Add this comma


Remove or comment this

Since we want the database to be created on the device that the app runs on, we will add some code to apply any
pending migrations to the local database on application startup. The first time that the app runs, this will take care of
creating the local database for us.
Right-click on App.xaml in Solution Explorer and select View Code
Add the highlighted lines of code from the following listing
1
2
3
4
5
6
7

using
using
using
using
using
using
using

System;
Microsoft.Data.Entity;
Windows.ApplicationModel;
Windows.ApplicationModel.Activation;
Windows.UI.Xaml;
Windows.UI.Xaml.Controls;
Windows.UI.Xaml.Navigation;

8
9
10
11
12
13
14
15
16
17
18
19

namespace EFGetStarted.UWP
{
sealed partial class App : Application
{
public App()
{
Microsoft.ApplicationInsights.WindowsAppInitializer.InitializeAsync(
Microsoft.ApplicationInsights.WindowsCollectors.Metadata |
Microsoft.ApplicationInsights.WindowsCollectors.Session);
this.InitializeComponent();
this.Suspending += OnSuspending;

20
21
22
23

using (var db = new BloggingContext())


{
db.Database.ApplyMigrations();

1.3. Getting Started on Universal Windows Platform

17

Entity Framework Documentation, Release 7.0.0

24

25

Tip: If you make future changes to your model, you can use the Add-Migration command to scaffold a new
migration to apply the corresponding changes to the database. Any pending migrations will be applied to the local
database on each device when the application starts.

1.3.6 Use your model


You can now use your model to perform data access.
Open MainPage.xaml
Add the page load handler and UI content highlighted below
1
2
3
4
5
6
7
8
9

<Page
x:Class="EFGetStarted.UWP.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:EFGetStarted.UWP"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
Loaded="Page_Loaded">

10
11
12
13
14
15
16
17
18
19
20
21
22
23
24

<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">


<StackPanel>
<TextBox Name="NewBlogUrl"></TextBox>
<Button Click="Add_Click">Add</Button>
<ListView Name="Blogs">
<ListView.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Url}" />
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</StackPanel>
</Grid>
</Page>

Now well add code to wire up the UI with the database


Right-click MainPage.xaml in Solution Explorer and select View Code
Add the highlighted code from the following listing
public sealed partial class MainPage : Page
{
public MainPage()
{
this.InitializeComponent();
}

1
2
3
4
5
6
7

private void Page_Loaded(object sender, RoutedEventArgs e)


{
using (var db = new BloggingContext())
{
Blogs.ItemsSource = db.Blogs.ToList();

8
9
10
11
12

18

Chapter 1. Getting Started

Entity Framework Documentation, Release 7.0.0

13

14
15

private void Add_Click(object sender, RoutedEventArgs e)


{
using (var db = new BloggingContext())
{
var blog = new Blog { Url = NewBlogUrl.Text };
db.Blogs.Add(blog);
db.SaveChanges();

16
17
18
19
20
21
22
23

Blogs.ItemsSource = db.Blogs.ToList();

24

25

26
27

You can now run the application to see it in action.


Debug Start Without Debugging
The application will build and launch
Enter a URL and click the Add button

1.3. Getting Started on Universal Windows Platform

19

Entity Framework Documentation, Release 7.0.0

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

1.4 Getting Started on OSX


This walkthrough will create a simple console application using ASP.NET 5 and the SQLite provider.
Note: This article was written for OS X Mavericks or newer. It uses beta 7 of ASP.NET and EF7.
You can find nightly builds of the EF7 code base hosted on https://www.myget.org/F/aspnetvnext/api/v2/ but the code
base is rapidly changing and we do not maintain up-to-date documentation for getting started.

In this article:

20

Prerequisites
Install ASP.NET 5
Create a new project
Create your model
Create your database
Use your model
Start your app
Workarounds

Chapter 1. Getting Started

Entity Framework Documentation, Release 7.0.0

Note: View this articles samples on GitHub.

1.4.1 Prerequisites
Minimum system requirements
Mono 4.0.2
OS X Mavericks
Caution: Known Issues
Bugs in Mono 4.0.2 may cause Entity Framework to crash when using async methods. This is resolved with
Mono 4.2.0, which is available as an alpha release (at time of writing).
Migrations on SQLite do not support more complex schema changes due to limitations in SQLite itself.
Bugs in beta 7. See Workarounds.
Migrations requires that you have a Startup class in your project. Issue #2357.

1.4.2 Install ASP.NET 5


A summary of steps to install ASP.NET 5 are included below. For a more up-to-date guide, follow the steps for
Installing ASP.NET 5 on Mac OS X. This will ensure you meet the following requirements.
The following steps will install dnvm, a command-line tool for installing the .NET Execution environment.
Install Homebrew
Use brew to install Mono
~ $ brew install mono

Run the dnvm

~ $ curl -sSL https://raw.githubusercontent.com/aspnet/Home/dev/dnvminstall.sh | DNX_BRANCH=

Verify dnvm has the latest version


~ $ dnvm upgrade

If you have trouble installing dnvm, consult this Getting Started guide.

1.4.3 Create a new project


Create a new folder ConsoleApp/ for your project. All files for the project should be contained in this folder.
~ $ mkdir ConsoleApp
~ $ cd ConsoleApp/

Create a new file project.json with the following contents


1
2
3
4
5
6
7

{
"dependencies": {
"EntityFramework.Sqlite": "7.0.0-beta7",
"EntityFramework.Commands": "7.0.0-beta7",
"Microsoft.Dnx.Runtime.Abstractions": "1.0.0-beta7"
},
"commands": {

1.4. Getting Started on OSX

21

Entity Framework Documentation, Release 7.0.0

"run": "ConsoleApp",
"ef": "EntityFramework.Commands"

8
9

},
"frameworks": {
"dnx451": { },
"dnxcore50": {
"dependencies": {
"System.Console": "4.0.0-beta-*"
}
}
}

10
11
12
13
14
15
16
17
18
19

Execute the following command to install the packages required for this project, including EntityFramework 7
and all its dependencies.
~/ConsoleApp/ $ dnu restore

Create a new file named Program.cs. Add the following contents to


1
2

// Program.cs
using System;

3
4
5
6
7
8
9
10
11
12
13

namespace ConsoleApp
{
public class Program
{
public void Main(string[] args)
{
Console.WriteLine("Hello dnx!");
}
}
}

To verify that this project has all dependencies and packages installed, perform the following steps:
Verify execution of the program works by running dnx run.
~/ConsoleApp/ $ dnx run
Hello dnx!

Verify that Entity Framework is installed by running dnx ef.


~/ConsoleApp/ $ dnx ef
_/\__
---==/
\\
___ ___
|.
\|\
| __|| __| | )
\\\
| _| | _|
\_/ | //|\\
|___||_|
/
\\\/\\
Entity Framework Commands 7.0.0-beta7-15540
Usage: ef [options] [command]
Options:
--version
-?|-h|--help

22

Show version information


Show help information

Chapter 1. Getting Started

Entity Framework Documentation, Release 7.0.0

Commands:
database
dbcontext
migrations

Commands to manage your database


Commands to manage your DbContext types
Commands to manage your migrations

Use "ef [command] --help" for more information about a command.

1.4.4 Create your model


With this new project, you are ready to begin using Entity Framework. We will create a simple console application
that allows us to write a blog post from the command line.
Create a new file called Model.cs All classes in follow steps will be added to this file.
1
2
3
4
5

using
using
using
using
using

System.Collections.Generic;
Microsoft.Data.Entity;
Microsoft.Dnx.Runtime;
Microsoft.Dnx.Runtime.Infrastructure;
Microsoft.Framework.DependencyInjection;

6
7
8

namespace ConsoleApp
{

Add a new class to represent the SQLite database. We will call this BloggingContext. Note that to configure this for SQLite, we must call UseSqlite() with a connection string pointing to the *.db file. Note
that we are making the path relative to the application path, rather than the current working directory of
the invoking process.
1
2
3
4

public class BloggingContext : DbContext


{
public DbSet<Blog> Blogs { get; set; }
public DbSet<Post> Posts { get; set; }

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)


{
var appEnv = CallContextServiceLocator.Locator.ServiceProvider
.GetRequiredService<IApplicationEnvironment>();
optionsBuilder.UseSqlite($"Data Source={ appEnv.ApplicationBasePath }/blog.db
}

6
7
8
9
10
11
12

Add classes to represent tables. Note that we will be using foreign keys to associate many posts to one blog.
1
2
3
4
5

public class Blog


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

public List<Post> Posts { get; set; }

7
8

9
10
11
12
13

public class Post


{
public int PostId { get; set; }
public string Title { get; set; }

1.4. Getting Started on OSX

23

Entity Framework Documentation, Release 7.0.0

public string Content { get; set; }

14
15

public int BlogId { get; set; }


public Blog Blog { get; set; }

16
17
18

To make sure the files are correct, you can compile the project on the command line by running dnu build
--quiet
~/ConsoleApp/ $ dnu build --quiet
Microsoft .NET Development Utility Mono-x86-1.0.0-beta6
Build succeeded.
0 Warning(s)
0 Error(s)
Total build time elapsed: 00:00:01.9609581
Total projects built: 1

1.4.5 Create your database


We can now use Entity Framework commands to create and manage the schema of our database.
Create the first migration. Execute the command below to generate your first migration. This will find our
context and models, and generate a migration for us in a folder named Migrations/
~/ConsoleApp/ $ dnx ef migrations add MyFirstMigration

Apply the migrations. You can now begin using the existing migration to create the database file and creates
the tables.
~/ConsoleApp/ $ dnx ef database update

This should create a new file, blog.db which contains two empty tables.

1.4.6 Use your model


Now that we have configured our model and created the database schema, we can use BloggingContext to create,
update, and delete objects.
1

using System;

2
3
4
5
6
7
8
9
10
11
12
13

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

14

Console.WriteLine();
Console.WriteLine("All blogs in database:");

15
16

24

Chapter 1. Getting Started

Entity Framework Documentation, Release 7.0.0

foreach (var blog in db.Blogs)


{
Console.WriteLine(" - {0}", blog.Url);
}

17
18
19
20

21

22

23
24

// TODO: Remove. Will be unnecessary when bug #2357 fixed


// See https://github.com/aspnet/EntityFramework/issues/2357
public class Startup
{
public void Configure() { }
}

25
26
27
28
29
30
31

1.4.7 Start your app


Run the application from the command line.
~/ConsoleApp/ $ dnx run
1 records saved to database
All blogs in database:
- http://blogs.msdn.com/adonet

After adding the new post, you can verify the data has been added by inspecting the SQLite database file, blog.db.

1.4.8 Workarounds
This demo was written for beta 7, which has bugs in it. The following workarounds will make this sample project
work for beta 7.
Add a Startup class to your project
When generating migrations, you may see this error message:

System.InvalidOperationException: A type named 'StartupProduction' or 'Startup' could not be found in

To get around this, add the following into your project.


1
2
3
4
5
6

// TODO: Remove. Will be unnecessary when bug #2357 fixed


// See https://github.com/aspnet/EntityFramework/issues/2357
public class Startup
{
public void Configure() { }
}

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

1.4. Getting Started on OSX

25

Entity Framework Documentation, Release 7.0.0

1.5 Getting Started on Linux


This walkthrough will create a simple console application using ASP.NET 5 and the SQLite provider.
Note: This article was written for beta 7 of ASP.NET and EF7.
You can find nightly builds of the EF7 code base hosted on https://www.myget.org/F/aspnetvnext/api/v2/ but the code
base is rapidly changing and we do not maintain up-to-date documentation for getting started.

In this article:

Prerequisites
Install ASP.NET 5
Create a new project
Create your model
Create your database
Use your model
Start your app
Workarounds

Note: View this articles samples on GitHub.

1.5.1 Prerequisites
Minimum system requirements
Mono 4.0.2
Ubuntu, Debian or one of their derivatives
Caution: Known Issues
Bugs in Mono 4.0.2 may cause Entity Framework to crash when using async methods. This is resolved with
Mono 4.2.0, which is available as an alpha release (at time of writing).
Migrations on SQLite do not support more complex schema changes due to limitations in SQLite itself.
Bugs in beta 7. See Workarounds.
Migrations requires that you have a Startup class in your project. Issue #2357.

1.5.2 Install ASP.NET 5


A summary of steps to install ASP.NET 5 are included below. For a more up-to-date guide, follow the steps for
Installing ASP.NET 5 on Linux. This will ensure you meet the following requirements.
The following steps will install dnvm, a command-line tool for installing the .NET Execution environment.
Install the required libraries
~ $ sudo apt-get install libunwind8 libssl-dev unzip

Install mono.

26

Chapter 1. Getting Started

Entity Framework Documentation, Release 7.0.0

~
~
~
~

$
$
$
$

sudo
echo
sudo
sudo

apt-key adv --keyserver keyserver.ubuntu.com --recv-keys 3FA7E0328081BFF6A14DA29AA6


"deb http://download.mono-project.com/repo/debian wheezy main" | sudo tee /etc/apt/
apt-get update
apt-get install mono-complete

Import required certificates for Nuget


~ $ mozroots --import --sync

Run the dnvm

~ $ curl -sSL https://raw.githubusercontent.com/aspnet/Home/dev/dnvminstall.sh | DNX_BRANCH=

Verify dnvm has the latest version


~ $ dnvm upgrade

If you have trouble installing dnvm, consult this Getting Started guide.

1.5.3 Create a new project


Create a new folder ConsoleApp/ for your project. All files for the project should be contained in this folder.
~ $ mkdir ConsoleApp
~ $ cd ConsoleApp/

Create a new file project.json with the following contents


1

{
"dependencies": {
"EntityFramework.Sqlite": "7.0.0-beta7",
"EntityFramework.Commands": "7.0.0-beta7",
"Microsoft.Dnx.Runtime.Abstractions": "1.0.0-beta7"
},
"commands": {
"run": "ConsoleApp",
"ef": "EntityFramework.Commands"
},
"frameworks": {
"dnx451": { },
"dnxcore50": {
"dependencies": {
"System.Console": "4.0.0-beta-*"
}
}
}

2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19

Execute the following command to install the packages required for this project, including EntityFramework 7
and all its dependencies.
~/ConsoleApp/ $ dnu restore

Create a new file named Program.cs. Add the following contents to


1
2

// Program.cs
using System;

3
4

namespace ConsoleApp

1.5. Getting Started on Linux

27

Entity Framework Documentation, Release 7.0.0

{
public class Program
{
public void Main(string[] args)
{
Console.WriteLine("Hello dnx!");
}
}

6
7
8
9
10
11
12
13

To verify that this project has all dependencies and packages installed, perform the following steps:
Verify execution of the program works by running dnx run.
~/ConsoleApp/ $ dnx run
Hello dnx!

Verify that Entity Framework is installed by running dnx ef.


~/ConsoleApp/ $ dnx ef
_/\__
---==/
\\
___ ___
|.
\|\
| __|| __| | )
\\\
| _| | _|
\_/ | //|\\
|___||_|
/
\\\/\\
Entity Framework Commands 7.0.0-beta7-15540
Usage: ef [options] [command]
Options:
--version
-?|-h|--help
Commands:
database
dbcontext
migrations

Show version information


Show help information

Commands to manage your database


Commands to manage your DbContext types
Commands to manage your migrations

Use "ef [command] --help" for more information about a command.

1.5.4 Create your model


With this new project, you are ready to begin using Entity Framework. We will create a simple console application
that allows us to write a blog post from the command line.
Create a new file called Model.cs All classes in follow steps will be added to this file.
1
2
3
4
5

using
using
using
using
using

System.Collections.Generic;
Microsoft.Data.Entity;
Microsoft.Dnx.Runtime;
Microsoft.Dnx.Runtime.Infrastructure;
Microsoft.Framework.DependencyInjection;

6
7
8

28

namespace ConsoleApp
{

Chapter 1. Getting Started

Entity Framework Documentation, Release 7.0.0

Add a new class to represent the SQLite database. We will call this BloggingContext. Note that to configure this for SQLite, we must call UseSqlite() with a connection string pointing to the *.db file. Note
that we are making the path relative to the application path, rather than the current working directory of
the invoking process.
1
2
3
4

public class BloggingContext : DbContext


{
public DbSet<Blog> Blogs { get; set; }
public DbSet<Post> Posts { get; set; }

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)


{
var appEnv = CallContextServiceLocator.Locator.ServiceProvider
.GetRequiredService<IApplicationEnvironment>();
optionsBuilder.UseSqlite($"Data Source={ appEnv.ApplicationBasePath }/blog.db
}

6
7
8
9
10
11
12

Add classes to represent tables. Note that we will be using foreign keys to associate many posts to one blog.
1
2
3
4
5

public class Blog


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

public List<Post> Posts { get; set; }

7
8

9
10
11
12
13
14

public class Post


{
public int PostId { get; set; }
public string Title { get; set; }
public string Content { get; set; }

15

public int BlogId { get; set; }


public Blog Blog { get; set; }

16
17
18

To make sure the files are correct, you can compile the project on the command line by running dnu build
--quiet
~/ConsoleApp/ $ dnu build --quiet
Microsoft .NET Development Utility Mono-x86-1.0.0-beta6
Build succeeded.
0 Warning(s)
0 Error(s)
Total build time elapsed: 00:00:01.9609581
Total projects built: 1

1.5.5 Create your database


We can now use Entity Framework commands to create and manage the schema of our database.

1.5. Getting Started on Linux

29

Entity Framework Documentation, Release 7.0.0

Create the first migration. Execute the command below to generate your first migration. This will find our
context and models, and generate a migration for us in a folder named Migrations/
~/ConsoleApp/ $ dnx ef migrations add MyFirstMigration

Apply the migrations. You can now begin using the existing migration to create the database file and creates
the tables.
~/ConsoleApp/ $ dnx ef database update

This should create a new file, blog.db which contains two empty tables.

1.5.6 Use your model


Now that we have configured our model and created the database schema, we can use BloggingContext to create,
update, and delete objects.
1

using System;

2
3
4
5
6
7
8
9
10
11
12
13

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

14

Console.WriteLine();
Console.WriteLine("All blogs in database:");
foreach (var blog in db.Blogs)
{
Console.WriteLine(" - {0}", blog.Url);
}

15
16
17
18
19
20

21

22

23
24

// TODO: Remove. Will be unnecessary when bug #2357 fixed


// See https://github.com/aspnet/EntityFramework/issues/2357
public class Startup
{
public void Configure() { }
}

25
26
27
28
29
30
31

1.5.7 Start your app


Run the application from the command line.
~/ConsoleApp/ $ dnx run
1 records saved to database

30

Chapter 1. Getting Started

Entity Framework Documentation, Release 7.0.0

All blogs in database:


- http://blogs.msdn.com/adonet

After adding the new post, you can verify the data has been added by inspecting the SQLite database file, blog.db.

1.5.8 Workarounds
This demo was written for beta 7, which has bugs in it. The following workarounds will make this sample project
work for beta 7.
Add a Startup class to your project
When generating migrations, you may see this error message:

System.InvalidOperationException: A type named 'StartupProduction' or 'Startup' could not be found in

To get around this, add the following into your project.


1
2
3
4
5
6

// TODO: Remove. Will be unnecessary when bug #2357 fixed


// See https://github.com/aspnet/EntityFramework/issues/2357
public class Startup
{
public void Configure() { }
}

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

1.5. Getting Started on Linux

31

Entity Framework Documentation, Release 7.0.0

32

Chapter 1. Getting Started

CHAPTER 2

Database Providers

The following providers are either available or being developed:


EntityFramework.SqlServer
EntityFramework.SQLite
EntityFramework.InMemory
EntityFramework.SqlServerCompact40
EntityFramework.SqlServerCompact35
EntityFramework.Npgsql

2.1 EntityFramework.SqlServer
Database Engine: Microsoft SQL Server (2008 onwards)
Platforms: Full .NET (4.5 onwards), DNX/ASP.NET 5 (dnx451 and dnxcore50), Mono (4.2.0 onwards)
Caution: Using this provider on Mono will make use of the Mono SQL Client implementation, which has a
number of known issues. For example, it does not support secure connections (SSL).
Status: Pre-release EntityFramework.SqlServer package on NuGet.org that supports the latest EF7 pre-release
Project Site: EntityFramework GitHub project
Getting Started: See Getting Started on Full .NET (Console, WinForms, WPF, etc.) or Getting Started on ASP.NET
5 for a walkthrough that uses this provider. The UnicornStore sample application also uses this provider.

2.2 EntityFramework.SQLite
Database Engine: SQLite (3.7 onwards)
Platforms: Full .NET (4.5 onwards), DNX/ASP.NET 5 (dnx451 and dnxcore50), Mono (4.2.0 onwards), UWP coming soon
Status: Pre-release EntityFramework.SQLite package on NuGet.org that supports the latest EF7 pre-release
Project Site: EntityFramework GitHub project
Getting Started: See Getting Started on Linux or Getting Started on OSX for a walkthrough that uses this provider

33

Entity Framework Documentation, Release 7.0.0

2.3 EntityFramework.InMemory
Database Engine: Built-in in-memory database (designed for testing purposes only)
Platforms: Full .NET (4.5 onwards), DNX/ASP.NET 5 (dnx451 and dnxcore50), Mono (4.2.0 onwards), UWP coming soon
Status: Pre-release EntityFramework.InMemory package on NuGet.org that supports the latest EF7 pre-release
Project Site: EntityFramework GitHub project
Getting Started: See the tests for the UnicornStore sample application for an example of using this provider.

2.4 EntityFramework.SqlServerCompact40
Database Engine: SQL Server Compact Edition 4.0
Platforms: Full .NET (4.5 onwards), DNX/ASP.NET 5 (dnx451 only)
Status: Pre-release EntityFramework.SqlServerCompact40 package on NuGet.org that supports the latest EF7 prerelease
Project Site: ErikEJ/EntityFramework7.SqlServerCompact GitHub Project
Getting Started: See the documentation for this project

2.5 EntityFramework.SqlServerCompact35
Database Engine: SQL Server Compact Edition 3.5
Platforms: Full .NET (4.5 onwards), DNX/ASP.NET 5 (dnx451 only)
Status: Pre-release EntityFramework.SqlServerCompact35 package on NuGet.org that supports the latest EF7 prerelease
Project Site: ErikEJ/EntityFramework7.SqlServerCompact GitHub Project
Getting Started: See the documentation for this project

2.6 EntityFramework.Npgsql
Database Engine: PostgreSql
Platforms: Full .NET (4.5 onwards), DNX/ASP.NET 5 (dnx451 only), Mono (4.2.0 onwards)
Status: Under active development. No official pre-release on NuGet.org yet.
Project Site: Npgsql.org
Getting Started: Some early documentation on using nightly builds is available.
Caution: This documentation is for EF7 onwards. For EF6.x and earlier release see http://msdn.com/data/ef.

34

Chapter 2. Database Providers

CHAPTER 3

Modeling

Note: This topic hasnt been written yet! You can track the status of this issue through our public GitHub issue
tracker. Learn how you can contribute on GitHub.
Caution: This documentation is for EF7 onwards. For EF6.x and earlier release see http://msdn.com/data/ef.

3.1 Default Conventions


Note: This topic hasnt been written yet! You can track the status of this issue through our public GitHub issue
tracker. Learn how you can contribute on GitHub.
Caution: This documentation is for EF7 onwards. For EF6.x and earlier release see http://msdn.com/data/ef.

3.2 Configuring Your Model


Entity Framework uses a set of Default Conventions to build a model based on the shape of your entity classes. You
can specify additional configuration to supplement and/or override what was discovered by convention.
Note: This article covers configuration that can be applied to a model targeting any data store and that which can be
applied when targeting any relational database. Providers may also enable configuration that is specific to a particular
data store. For documentation on provider specific configuration see the the Database Providers section.
In this article:
Methods of configuration
Fluent API
Data Annotations
Keys
Indexes
Required
Generated Properties (Identity, Computed, Store Defaults, etc.)
35

Entity Framework Documentation, Release 7.0.0

Maximum Length
Concurrency Tokens
Ignoring Types and Properties
Relational database configuration
Relational table
Relational column
Relational data type
View this articles samples on GitHub.
Note: This article uses EF 7.0.0-beta7 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/api/v2/ but the code
base is rapidly changing and we do not maintain up-to-date documentation for getting started.

3.2.1 Methods of configuration


Fluent API
You can override the OnModelCreating method in your derived context and use the ModelBuilder API to
configure your model. This is the most powerful method of configuration and allows configuration to be specified
without modifying your entity classes.
class MyContext : DbContext
{
public DbSet<Blog> Blogs { get; set; }

1
2
3
4

protected override void OnModelCreating(ModelBuilder modelBuilder)


{
modelBuilder.Entity<Blog>()
.Property(b => b.Url)
.Required();
}

5
6
7
8
9
10

11

Data Annotations
Caution: Data Annotations are not yet fully implemented in Entity Framework 7. You can still add annotations
to your entity classes so that they are used by other frameworks (such as ASP.NET MVC), but Entity Framework
will not process these annotations. You can track support for Data Annotations on GitHub.

3.2.2 Keys
A key serves as the primary unique identifier for each entity instance. When using a relational database this maps to
the concept of a primary key.
The following fragment shows how to configure a single property to be the key of an entity. In this case
LicensePlate is the primary key of Car but will not have been detected by the default conventions.

36

Chapter 3. Modeling

Entity Framework Documentation, Release 7.0.0

1
2
3

class MyContext : DbContext


{
public DbSet<Car> Cars { get; set; }

protected override void OnModelCreating(ModelBuilder modelBuilder)


{
modelBuilder.Entity<Car>()
.Key(c => c.LicensePlate);
}

5
6
7
8
9
10

11
12
13
14

class Car
{
public string LicensePlate { get; set; }

15

public string Make { get; set; }


public string Model { get; set; }

16
17
18

Building on the previous example, lets say that the primary key of Car is made up of two properties (State and
LicensePlate).
1
2
3

class MyContext : DbContext


{
public DbSet<Car> Cars { get; set; }

protected override void OnModelCreating(ModelBuilder modelBuilder)


{
modelBuilder.Entity<Car>()
.Key(c => new { c.State, c.LicensePlate });
}

5
6
7
8
9
10

11
12
13
14
15

class Car
{
public string State { get; set; }
public string LicensePlate { get; set; }

16

public string Make { get; set; }


public string Model { get; set; }

17
18
19

3.2.3 Indexes
Indexes are a common concept across many data stores. While their implementation in the data store may vary, they
are used to make lookups based on a column (or set of columns) more efficient.
The following code shows how to specify an index on a single property. By default, indexes are non-unique.
1
2
3

class MyContext : DbContext


{
public DbSet<Blog> Blogs { get; set; }

4
5
6
7
8

protected override void OnModelCreating(ModelBuilder modelBuilder)


{
modelBuilder.Entity<Blog>()
.Index(b => b.Url);

3.2. Configuring Your Model

37

Entity Framework Documentation, Release 7.0.0

10
11

public class Blog


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

12
13
14
15
16

You can also specify that an idex should be unique, meaning that no two entities can have the same value(s) for the
given property(s).
modelBuilder.Entity<Blog>()
.Index(b => b.Url)
.Unique();

1
2
3

You can also specify an index over more than one column.
class MyContext : DbContext
{
public DbSet<Person> People { get; set; }

1
2
3
4

protected override void OnModelCreating(ModelBuilder modelBuilder)


{
modelBuilder.Entity<Person>()
.Index(p => new { p.FirstName, p.LastName });
}

5
6
7
8
9

10
11

public class Person


{
public int PersonId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}

12
13
14
15
16
17

3.2.4 Required
By default, a property whose type can contain null will be configured as optional (i.e. CLR reference types such as
string, int?, byte[], etc.). However, these properties can be configured to be required.
class MyContext : DbContext
{
public DbSet<Blog> Blogs { get; set; }

1
2
3
4

protected override void OnModelCreating(ModelBuilder modelBuilder)


{
modelBuilder.Entity<Blog>()
.Property(b => b.Url)
.Required();
}

5
6
7
8
9
10

11
12

public class Blog


{
public int BlogId { get; set; }

13
14
15

38

Chapter 3. Modeling

Entity Framework Documentation, Release 7.0.0

public string Url { get; set; }

16

17

Note: A property whose type can not contain null can not be configured as optional (i.e. CLR value types such as
int, bool, decimal, etc.).

3.2.5 Generated Properties (Identity, Computed, Store Defaults, etc.)


Note: Sentinel Values
EF uses a sentinel value to detect whether a value has been specified or not. By default the sentinel value is the CLR
default for the property type (null for string, 0 for int, etc.).
If the property is assigned something other than the sentinel value, then EF will attempt to save the specified value to
the database regardless of the value generation strategy that is configured.
You can change the sentinel value for a given property. The most common case for doing this is a property that does
not use value generation where you want to be able to save a record with the default sentinel value. For example, if
you want to be able to save the value 0 for an integer primary key, you would need to change the sentinel value to
something other than 0.
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
// Note there is no Fluent API for sentinel value in Beta6
//
so we must drop down to metadata
modelBuilder.Entity<Blog>()
.Property(b => b.BlogId)
.Metadata.SentinelValue = -1;
}

1
2
3
4
5
6
7
8

There are three value generation patterns that can be used for properties.
No value generation
No value generation means that you will always supply a valid value to be saved to the database.
class MyContext : DbContext
{
public DbSet<Blog> Blogs { get; set; }

1
2
3
4

protected override void OnModelCreating(ModelBuilder modelBuilder)


{
modelBuilder.Entity<Blog>()
.Property(b => b.BlogId)
.ValueGeneratedNever();
}

5
6
7
8
9
10

11
12

public class Blog


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

13
14
15
16
17
18

3.2. Configuring Your Model

39

Entity Framework Documentation, Release 7.0.0

Value generated on add


Value generated on add means that if you dont specify a value one will be generated for you. This value may be
generated client side by EF, or in the database.
class MyContext : DbContext
{
public DbSet<Blog> Blogs { get; set; }

1
2
3
4

protected override void OnModelCreating(ModelBuilder modelBuilder)


{
modelBuilder.Entity<Blog>()
.Property(b => b.BlogId)
.ValueGeneratedOnAdd();
}

5
6
7
8
9
10

11
12

public class Blog


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

13
14
15
16
17
18

Value generated on add or update


Value generated on add or update means that a new value is generated every time the record is saved (insert or update).
class MyContext : DbContext
{
public DbSet<Blog> Blogs { get; set; }

1
2
3
4

protected override void OnModelCreating(ModelBuilder modelBuilder)


{
modelBuilder.Entity<Blog>()
.Property(b => b.LastUpdated)
.ValueGeneratedOnAddOrUpdate();
}

5
6
7
8
9
10

11
12

public class Blog


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

13
14
15
16
17
18
19

3.2.6 Maximum Length


Configuring a maximum length provides a hint to the data store about the appropriate data type to use for a given
property.
The following code allows the store to choose an appropraite data type for Blog.Url based on the fact it should only
ever contain 500 characters. When targetting SQL Server this would result in the nvarchar(500) data type being
used.

40

Chapter 3. Modeling

Entity Framework Documentation, Release 7.0.0

1
2
3

class MyContext : DbContext


{
public DbSet<Blog> Blogs { get; set; }

protected override void OnModelCreating(ModelBuilder modelBuilder)


{
modelBuilder.Entity<Blog>()
.Property(b => b.Url)
.MaxLength(500);
}

5
6
7
8
9
10
11

12
13
14
15
16
17

public class Blog


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

Note: Entity Framework does not do any validation of maximum length before passing data to the provider. It is up
to the provider or data store to validate if appropriate.
For example, when targetting SQL Server, exceding the maximum length will result in an exception as the data type
of the underlying column will not allow excess data to be stored.

3.2.7 Concurrency Tokens


If a property is configured as a concurrency token then EF will check that no other user has modified that value in the
database when saving changes to that record. EF uses an optimistic concurrency pattern, meaning it will assume the
value has not changed and try to save the data, but throw if it finds the value has been changed.
For example we may want to configure SocialSecurityNumber on Person to be a concurrency token. This means that if one user tries to save some changes to a Person, but another user has changed the
SocialSecurityNumber then an exception will be thrown. This may be desirable so that our application can
prompt the user to ensure this record still represents the same actual person before saving their changes.
1
2
3

class MyContext : DbContext


{
public DbSet<Person> People { get; set; }

protected override void OnModelCreating(ModelBuilder modelBuilder)


{
modelBuilder.Entity<Person>()
.Property(p => p.SocialSecurityNumber)
.ConcurrencyToken();
}

5
6
7
8
9
10
11

12
13
14
15
16
17
18

public class Person


{
public int PersonId { get; set; }
public string SocialSecurityNumber { get; set; }
public string Name { get; set; }
}

3.2. Configuring Your Model

41

Entity Framework Documentation, Release 7.0.0

How concurrency tokens work in EF


Data stores can enforce concurrency tokens by checking that any record being updated or deleted still has the same
value for the concurrency token that was assigned when the context originally loaded the data from the database.
For example, relational database achieve this by including the concurrency token in the WHERE clause of any UPDATE
or DELETE commands and checking the number of rows that were affected. If the concurrency token still matches
then one row will be updated. If the value in the database has changed, then no rows are updated.
UPDATE [Person] SET [Name] = @p1
WHERE [PersonId] = @p0 AND [SocialSecurityNumber] = @p2;

3.2.8 Ignoring Types and Properties


EF uses conventions to discover the types and properties that should be included in your model. Including a type or
property in your model means that it will be saved to and queried from the database.
Ignore a type
The following code shows how to ignore an entire type from your model.
class MyContext : DbContext
{
public DbSet<Blog> Blogs { get; set; }

1
2
3
4

protected override void OnModelCreating(ModelBuilder modelBuilder)


{
modelBuilder.Ignore<BlogMetadata>();
}

5
6
7
8

9
10

public class Blog


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

11
12
13
14
15

public BlogMetadata Metadata { get; set; }

16

17

Ignore a property
The following code shows how to ignore a property from a type.
class MyContext : DbContext
{
public DbSet<Blog> Blogs { get; set; }

1
2
3
4

protected override void OnModelCreating(ModelBuilder modelBuilder)


{
modelBuilder.Entity<Blog>()
.Ignore(b => b.LoadedFromDatabase);
}

5
6
7
8
9

10
11

public class Blog

12

42

Chapter 3. Modeling

Entity Framework Documentation, Release 7.0.0

13

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

14
15
16

public DateTime LoadedFromDatabase { get; set; }

17
18

3.2.9 Relational database configuration


The configuration in this section is applicable to relational databases in general. The extension methods shown here
will become available when you install a relational database provider (due to the shared EntityFramework.Relational
package).
Note: Not all relational database will support all configuration shown here. For example, SQLite does not support
the concept of schemas.

Relational table
The following code maps the Blog class to a blogs table in the database.
1
2
3

class MyContext : DbContext


{
public DbSet<Blog> Blogs { get; set; }

protected override void OnModelCreating(ModelBuilder modelBuilder)


{
modelBuilder.Entity<Blog>()
.ToTable("blogs");
}

5
6
7
8
9
10

11
12
13
14
15
16

public class Blog


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

You can also specify a schema that the table belongs to.
1
2

modelBuilder.Entity<Blog>()
.ToTable("blogs", schema: "blogging");

Relational column
The following code maps the Blog.BlogId property to a blog_id column in the database.
1
2
3

class MyContext : DbContext


{
public DbSet<Blog> Blogs { get; set; }

4
5
6
7
8

protected override void OnModelCreating(ModelBuilder modelBuilder)


{
modelBuilder.Entity<Blog>()
.Property(b => b.BlogId)

3.2. Configuring Your Model

43

Entity Framework Documentation, Release 7.0.0

.HasColumnName("blog_id");

10

11
12

public class Blog


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

13
14
15
16
17

Relational data type


The following code specifies that the column for Blog.Url should use the varchar(200) datatype.
class MyContext : DbContext
{
public DbSet<Blog> Blogs { get; set; }

1
2
3
4

protected override void OnModelCreating(ModelBuilder modelBuilder)


{
modelBuilder.Entity<Blog>()
.Property(b => b.Url)
.HasColumnType("varchar(200)");
}

5
6
7
8
9
10

11
12

public class Blog


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

13
14
15
16
17

If you are targetting more than one relational provider with the same model then you probably want to specify a data
type for each provider rather than a global one to be used for all relational providers.
modelBuilder.Entity<Blog>()
.Property(b => b.Url)
.HasSqlServerColumnType("varchar(200)");

1
2
3

44

Chapter 3. Modeling

CHAPTER 4

Contribute

We accept pull requests! But youre more likely to have yours accepted if you follow the guidelines for contributing.

45

S-ar putea să vă placă și