警告

This documentation is for EF7 onwards. For EF6.x and earlier release see http://msdn.com/data/ef. 本文档是基于EF7版本.对于EF6.x及更早的版本请参见 http://msdn.com/data/ef.

注解

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

Getting Started on Linux

This walkthrough will create a simple console application using ASP.NET 5 and the SQLite provider.

In this article:

小技巧

You can view this article’s sample on GitHub.

Prerequisites

Minimum system requirements
  • Ubuntu, Debian or one of their derivatives

警告

Known Issues

  • DNX-coreclr will die silentily if you are missing the ICU library. Make sure to install all dependencies listed in the install guide. (See Issue dnx#2875)
  • Migrations on SQLite do not support more complex schema changes due to limitations in SQLite itself.
  • Package names are case-sensitive on Linux and OS X due to the case-sensitive filesystem. Make sure to use EntityFramework.Sqlite not EntityFramework.SQLite in your project.json file. (See Issue dotnet/cli#236)

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 unzip curl libunwind8 gettext libssl-dev libcurl3-dev zlib1g libicu-dev
    
  • Install dnvm

    ~ $ curl -sSL https://raw.githubusercontent.com/aspnet/Home/dev/dnvminstall.sh | DNX_BRANCH=dev sh && source ~/.dnx/dnvm/dnvm.sh
    
  • Install the latest version of DNX. The -r selects the CoreCLR runtime. Linux also supports the Mono runtime, but it is not used in this tutorial.

    ~ $ dnvm upgrade -r coreclr
    

If you have trouble installing dnvm, consult Installing ASP.NET 5 on Linux.

Install SQLite

EntityFramework.SQLite requires libsqlite3. This may not be installed by default.

On Ubuntu 14, install the SQLite library.

~ $ sudo apt-get install libsqlite3-dev

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
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    {
        "dependencies": {
            "EntityFramework.Sqlite": "7.0.0-rc1-final",
            "EntityFramework.Commands": "7.0.0-rc1-final",
            "Microsoft.Extensions.PlatformAbstractions": "1.0.0-rc1-final"
        },
        "commands": {
            "run": "ConsoleApp",
            "ef": "EntityFramework.Commands"
        },
        "frameworks": {
            "dnxcore50": {
                "dependencies": {
                    "System.Console": "4.0.0-beta-*"
                }
            }
        }
    }
    
  • 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
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    using System;
    
    namespace ConsoleApp
    {
        public class Program
        {
            public static void Main()
            {
                Console.WriteLine("Hello EF!");
            }
        }
    }
    

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 EF!
    
  • Verify that Entity Framework is installed by running dnx ef.

    ~/ConsoleApp/ $ dnx ef
    
                         _/\__
                   ---==/    \\
             ___  ___   |.    \|\
            | __|| __|  |  )   \\\
            | _| | _|   \_/ |  //|\\
            |___||_|       /   \\\/\\
    
    Entity Framework Commands 7.0.0-rc1-16297
    
    Usage: dnx ef [options] [command]
    
    Options:
      --version     Show version information
      -?|-h|--help  Show help information
    
    Commands:
      database    Commands to manage your database
      dbcontext   Commands to manage your DbContext types
      migrations  Commands to manage your migrations
    
    Use "dnx ef [command] --help" for more information about a command.
    

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 the following steps will be added to this file.

    1
    2
    3
    4
    5
    6
    7
    using System.Collections.Generic;
    using System.IO;
    using Microsoft.Data.Entity;
    using Microsoft.Extensions.PlatformAbstractions;
    
    namespace ConsoleApp
    {
    
  • Add a new class to represent the SQLite database.

    We will call this BloggingContext. The call to UseSqlite() configures EF to point to a *.db file in the same folder as the project.json file for our project.

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
        public class BloggingContext : DbContext
        {
            public DbSet<Blog> Blogs { get; set; }
            public DbSet<Post> Posts { get; set; }
    
            protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
            {
                var path = PlatformServices.Default.Application.ApplicationBasePath;
                optionsBuilder.UseSqlite("Filename=" + Path.Combine(path, "blog.db"));
            }
        }
    
  • 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
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
        public class Blog
        {
            public int BlogId { get; set; }
            public string Url { get; set; }
            public string Name { get; set; }
    
            public List<Post> Posts { get; set; }
        }
    
        public class Post
        {
            public int PostId { get; set; }
            public string Title { get; set; }
            public string Content { get; set; }
    
            public int BlogId { get; set; }
            public Blog Blog { get; set; }
        }
    
  • 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 CoreClr-x64-1.0.0-rc1-16137
    
    Building ConsoleApp for DNXCore,Version=v5.0
    
    Build succeeded.
        0 Warning(s)
        0 Error(s)
    
    Time elapsed 00:00:03.7102187
    Total build time elapsed: 00:00:03.8096587
    Total projects built: 1
    

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.

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
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
using System;

namespace ConsoleApp
{
    public class Program
    {
        public static void Main()
        {
            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);

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

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.