CREATE DATABASE [EFCore_dbfirst]
GO

USE [EFCore_dbfirst]
GO

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

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

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

先创建数据库

创建一个新项目

这里我们选择  ASP.NET Core Web Application (.NET Core) 

 

 ASP.NET Core  (Database First)

 

这里选择Web 应用程序,然后更改身份验证 改为 不进行身份验证

ASP.NET Core  (Database First)

 

添加包

工具‣的NuGet包管理器‣包管理器控制台

ASP.NET Core  (Database First)

  • Run Install-Package Microsoft.EntityFrameworkCore
  • Run Install-Package Microsoft.EntityFrameworkCore.SqlServer
  • Run Install-Package Microsoft.EntityFrameworkCore.Tools –Pre
  • Run Install-Package Microsoft.EntityFrameworkCore.SqlServer.Design

引用好以后我们在project.json -> tools 节点加上 "Microsoft.EntityFrameworkCore.Tools": "1.0.0-preview2-final"

"tools": {
        "Microsoft.EntityFrameworkCore.Tools": "1.0.0-preview2-final",
        "BundlerMinifier.Core": "2.0.238",
        "Microsoft.AspNetCore.Razor.Tools": "1.0.0-preview2-final",
        "Microsoft.AspNetCore.Server.IISIntegration.Tools": "1.0.0-preview2-final"
    },

根据数据库生成EF

还是使用程序包管理控制台

执行 

 Scaffold-DbContext  "Data Source=.;Initial Catalog=EFCore_dbfirst;User ID=sa;Password=sa.123" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models

分析一下这条命令   

   Scaffold-DbContext 命令名称  +"数据库连接字符串"  + Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models      ( 这貌似是Provider参数)

 

注意
运行以下命令来创建从现有数据库的模型。如果您收到一个错误, ‘Scaffold-DbContext’ is not recognized as the name of a cmdlet ,请重新打开Visual Studio中。

执行成功后生成了如下代码

ASP.NET Core  (Database First)

注册与依赖注入上下文(Register your context with dependency injection)

在ASP.NET Core,配置通常在 Startup.cs。为了符合这种模式,我们将移动数据库配置 到Startup.cs中。

EFCore_dbfirstContext 中 

删除如下代码

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            //#warning To protect potentially sensitive information in your connection string, you should move it out of source code. See http://go.microsoft.com/fwlink/?LinkId=723263 for guidance on storing connection strings.
            optionsBuilder.UseSqlServer(@"Data Source=.;Initial Catalog=EFCore_dbfirst;User ID=sa;Password=sa.123");
        }

添加如下代码

  public EFCore_dbfirstContext(DbContextOptions<EFCore_dbfirstContext> options)
            : base(options)
        {
        }

 

在 Startup.cs中  的 ConfigureServices方法 增加代码

这是增加后的效果

   // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext<EFCore_dbfirstContext>(options =>
                options.UseSqlServer("Data Source =.; Initial Catalog = EFCore_dbfirst; User ID = sa; Password = sa.123"));

            // Add framework services.
            services.AddMvc();
        }

 开始写代码

添加 BlogsController

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using EFCoreDbFirst.Models;

// For more information on enabling MVC for empty projects, visit http://go.microsoft.com/fwlink/?LinkID=397860

namespace EFCoreDbFirst.Controllers
{
    public class BlogsController : Controller
    {
        private EFCore_dbfirstContext _context;

        public BlogsController(EFCore_dbfirstContext context)
        {
            _context = context;
        }

        public IActionResult Index()
        {
            return View(_context.Blog.ToList());
        }

        public IActionResult Create()
        {
            return View();
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public IActionResult Create(Blog blog)
        {
            if (ModelState.IsValid)
            {
                _context.Blog.Add(blog);
                _context.SaveChanges();
                return RedirectToAction("Index");
            }

            return View(blog);
        }
    }
}
BlogsController

相关文章: