Today I will create a small .net core console application  step by step, to show how to use Entity Framework Core, Configurateion and Dependance Injection.

Prerequisites:

Windows 10,

Visual Studio 2017,

.Net Core SDK 2.0 For Windows,

MS SQLServer Express 2017.

Demo:

https://github.com/zuolun/EF_CodeFirst__Config_DI_ConsoleApplication

1Create a .net Core Console Application

2 Use Nuget Package Manager to install EntityFrameCore.

Tools > NuGet Package Manager > Package Manager Console

Run

install-package Microsoft.EntityFrameworkCore

 

3Create a Data Model,This walkthrough just create one data entity, it called Flow.

using System;
using System.ComponentModel.DataAnnotations;

namespace EFCodeFistConfigDIConsoleApp.Model
{
    class Flow
    {
        [Key]
        public Guid Id { get; set; }
        [MaxLength(20)]
        [Required]
        public string Name { get; set; }
    }
}

4Create the DbContext

using Microsoft.EntityFrameworkCore;

namespace EFCodeFistConfigDIConsoleApp
{
    class FlowDBContext:DbContext
    {
        public DbSet<Flow> Flows { get; set; }
    }
}

5Install  Microsoft.Extensions.DependencyInjection

Tools > NuGet Package Manager > Package Manager Console

Run

install-package Microsoft.Extensions.DependencyInjection

6Register DbContext to the container's services,and get the DbContext instance from the container.We try to add an item to the DbContext and SaveChanges.

using EFCodeFistConfigDIConsoleApp.Model;
using Microsoft.Extensions.DependencyInjection;
using System;

namespace EFCodeFistConfigDIConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            var serviceCollection = new ServiceCollection();
            var services = serviceCollection.AddDbContext<FlowDBContext>().BuildServiceProvider();
            var dbContext = services.GetService<FlowDBContext>();
            var flow = new Flow { Id = Guid.NewGuid(), Name = "f1" };
            dbContext.Flows.Add(flow);
            dbContext.SaveChanges();
            Console.WriteLine("Hello World!");
            Console.ReadLine();
        }
    }
}

We run the application, it throwed a Exception:"No database provider has been configured for this DbContext. A provider can be configured by overriding the DbContext.OnConfiguring method or by using AddDbContext on the application service provider. If AddDbContext is used, then also ensure that your DbContext type accepts a DbContextOptions<TContext> object in its constructor and passes it to the base constructor for DbContext."

7Install the package for the database provide you want to target.This walkthrough use SQL Server.

Tools > NuGet Package Manager > Package Manager Console

Run

install-package Microsoft.EntityFrameworkCore.SqlServer

7Add constructor the FlowDbContext.

using EFCodeFistConfigDIConsoleApp.Model;
using Microsoft.EntityFrameworkCore;

namespace EFCodeFistConfigDIConsoleApp
{
    class FlowDbContext:DbContext
    {
        public DbSet<Flow> Flows { get; set; }

        public FlowDbContext(DbContextOptions options) : base(options)
        {
        }
    }
}

8Set data base provider,data base connection string while add DbContext to CollectionServers.

 

var services = serviceCollection.AddDbContext<FlowDbContext>(op => op.UseSqlServer("Data Source=.\\SQLEXPRESS;Initial Catalog=FlowDb;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False"))
                .BuildServiceProvider();

9We run the application, it throw an exception "'Cannot open database "FlowDb" requested by the login. The login failed.
Login failed for user …". That's because the data base 'FlowDb' has not been created.

10It's time to create database.To do this, add an initail migration.Install EF Core Tools.

Tools > NuGet Package Manager > Package Manager Console

Run

Install-package Microsoft.EntityFrameworkCore.Tools

11Run the appropriate command to add initail migration.

Tools > NuGet Package Manager > Package Manager Console

Run

PM> Add-Migration InitialCreate

But there is some error occure."Unable to create an object of type 'FlowDbContext'. Add an implementation of 'IDesignTimeDbContextFactory<FlowDbContext>' to the project, or see https://go.microsoft.com/fwlink/?linkid=851728 for additional patterns supported at design time."

12Add implement of IDesignTimeDbContextFactory<FlowDbContext>.

using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Design;

namespace EFCodeFistConfigDIConsoleApp
{
    class DesignTimeFlowDbContextFactory : IDesignTimeDbContextFactory<FlowDbContext>
    {
        public FlowDbContext CreateDbContext(string[] args)
        {
            var optionsBuilder = new DbContextOptionsBuilder<FlowDbContext>();
            optionsBuilder.UseSqlServer("Data Source=.\\SQLEXPRESS;Initial Catalog=FlowDb;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False");
            return new FlowDbContext(optionsBuilder.Options);
        }
    }
}

13Add initial migration again.

Tools > NuGet Package Manager > Package Manager Console

Run

PM> Add-Migration InitialCreate

This time we success.

14.Run "Update-Database", to create database.

Tools > NuGet Package Manager > Package Manager Console

Run

update-database

15.Run this application, it runs well.We can see a data added to the database "FlowDb".

16Up to now, we set data base connection by hard code.We use configuration instead of hard code.To do this, intall package Microsoft.Extensions.Options.ConfigurationExtensions.In ths walkthrough, we write the configuration to a json file.

Tools > NuGet Package Manager > Package Manager Console

Run

Install-Package Microsoft.Extensions.Options.ConfigurationExtensions
PM> Install-Package Microsoft.Extensions.Configuration.Json

17Add a json file to project, it names AppSettings.json(The file name is up to you, you can take a name whatever you like.), and Set it's advanced property "Copy to Output Directory" to "Copy if newer".

{
  "ConnectionStrings": {
    "BloggingDatabase": "Data Source=IANSUFRACELAPTO\\SQLEXPRESS;Initial Catalog=FlowDb;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False"
  }
}

18We read the configuration from the json file.

using EFCodeFistConfigDIConsoleApp.Model;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.IO;

namespace EFCodeFistConfigDIConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            var serviceCollection = new ServiceCollection();
            var configurationBuilder = new ConfigurationBuilder();
            configurationBuilder.SetBasePath(Directory.GetCurrentDirectory());
            configurationBuilder.AddJsonFile("AppSettings.json");
            var configurageRoot = configurationBuilder.Build();
            var dbConnectionStr = configurageRoot.GetConnectionString("BloggingDatabase");
            var services = serviceCollection.AddDbContext<FlowDbContext>(op => op.UseSqlServer(dbConnectionStr))
                .BuildServiceProvider();
            var dbContext = services.GetService<FlowDbContext>();
            var flow = new Flow { Id = Guid.NewGuid(), Name = "f1" };
            dbContext.Flows.Add(flow);
            dbContext.SaveChanges();
            Console.WriteLine("Hello World!");
            Console.ReadLine();
        }
    }
}

 

posted on 2018-04-21 18:37  IanHou  阅读(293)  评论(0)    收藏  举报