Documente Academic
Documente Profesional
Documente Cultură
Release 7.0.0
Microsoft
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
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
Contents
CHAPTER 1
Getting Started
Caution: This documentation is for EF7 onwards. For EF6.x and earlier release see http://msdn.com/data/ef.
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
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
// Visual Studio 2012 | Use the SQL Express instance created by Visual Studio
// optionsBuilder.UseSqlServer(@"Server=.\SQLEXPRESS;Database=EFGetStarted.ConsoleApp;Tru
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
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
Caution: This documentation is for EF7 onwards. For EF6.x and earlier release see http://msdn.com/data/ef.
1.2.1 Prerequisites
The following items are required to complete this walkthrough:
Visual Studio 2015
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
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
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
using Microsoft.Data.Entity;
using EFGetStarted.AspNet5.Models;
5
6
7
8
services.AddEntityFramework()
.AddSqlServer()
.AddDbContext<BloggingContext>(options => options.UseSqlServer(connection));
9
10
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
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult Create(Blog blog)
{
if (ModelState.IsValid)
26
27
28
29
30
10
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.
@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
11
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
12
Caution: This documentation is for EF7 onwards. For EF6.x and earlier release see http://msdn.com/data/ef.
13
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.
14
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
15
try
{
17
18
19
20
21
22
23
optionsBuilder.UseSqlite($"Data source={databaseFilePath}");
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
16
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
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
17
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.
<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
1
2
3
4
5
6
7
8
9
10
11
12
18
13
14
15
16
17
18
19
20
21
22
23
Blogs.ItemsSource = db.Blogs.ToList();
24
25
26
27
19
Caution: This documentation is for EF7 onwards. For EF6.x and earlier release see http://msdn.com/data/ef.
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
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.
If you have trouble installing dnvm, consult this Getting Started guide.
{
"dependencies": {
"EntityFramework.Sqlite": "7.0.0-beta7",
"EntityFramework.Commands": "7.0.0-beta7",
"Microsoft.Dnx.Runtime.Abstractions": "1.0.0-beta7"
},
"commands": {
21
"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
// 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!
22
Commands:
database
dbcontext
migrations
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
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
7
8
9
10
11
12
13
23
14
15
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
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.
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
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
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:
Caution: This documentation is for EF7 onwards. For EF6.x and earlier release see http://msdn.com/data/ef.
25
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
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.
Install mono.
26
~
~
~
~
$
$
$
$
sudo
echo
sudo
sudo
If you have trouble installing dnvm, consult this Getting Started guide.
{
"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
// Program.cs
using System;
3
4
namespace ConsoleApp
27
{
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!
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
{
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
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
7
8
9
10
11
12
13
14
15
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
29
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.
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
25
26
27
28
29
30
31
30
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:
Caution: This documentation is for EF7 onwards. For EF6.x and earlier release see http://msdn.com/data/ef.
31
32
CHAPTER 2
Database Providers
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
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 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.
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.
1
2
3
4
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
1
2
3
5
6
7
8
9
10
11
12
13
14
class Car
{
public string LicensePlate { get; set; }
15
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
5
6
7
8
9
10
11
12
13
14
15
class Car
{
public string State { get; set; }
public string LicensePlate { get; set; }
16
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
4
5
6
7
8
37
10
11
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
5
6
7
8
9
10
11
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
5
6
7
8
9
10
11
12
13
14
15
38
Chapter 3. Modeling
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.).
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
5
6
7
8
9
10
11
12
13
14
15
16
17
18
39
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
40
Chapter 3. Modeling
1
2
3
5
6
7
8
9
10
11
12
13
14
15
16
17
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.
5
6
7
8
9
10
11
12
13
14
15
16
17
18
41
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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
5
6
7
8
9
10
11
12
42
Chapter 3. Modeling
13
{
public int BlogId { get; set; }
public string Url { get; set; }
14
15
16
17
18
Relational table
The following code maps the Blog class to a blogs table in the database.
1
2
3
5
6
7
8
9
10
11
12
13
14
15
16
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
4
5
6
7
8
43
.HasColumnName("blog_id");
10
11
12
13
14
15
16
17
1
2
3
4
5
6
7
8
9
10
11
12
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