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) 

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

添加包

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

  • 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中。

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

注册与依赖注入上下文(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

添加 Index.cshtml

@model IEnumerable<EFCoreDbFirst.Models.Blog>

@{
ViewBag.Title = "Blogs";
} <h2>Blogs</h2> <p>
<a asp-controller="Blogs" asp-action="Create">Create New</a>
</p> <table class="table">
<tr>
<th>Id</th>
<th>Url</th>
</tr> @foreach (var item in Model)
{
<tr>
<td>
@Html.DisplayFor(modelItem => item.BlogId)
</td>
<td>
@Html.DisplayFor(modelItem => item.Url)
</td>
</tr>
}
</table>

Index.cshtml

添加 Create.cshtml

@model  EFCoreDbFirst.Models.Blog

@{
ViewBag.Title = "New Blog";
} <h2>@ViewData["Title"]</h2> <form asp-controller="Blogs" asp-action="Create" method="post" class="form-horizontal" role="form">
<div class="form-horizontal">
<div asp-validation-summary="All" class="text-danger"></div>
<div class="form-group">
<label asp-for="Url" class="col-md-2 control-label"></label>
<div class="col-md-10">
<input asp-for="Url" class="form-control" />
<span asp-validation-for="Url" class="text-danger"></span>
</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>
</form>

Create.cshtml

来看看效果

ASP.NET Core (Database First)的更多相关文章

  1. ASP.NET Core 开发-Entity Framework (EF) Core 1.0 Database First

    ASP.NET Core 开发-Entity Framework Core 1.0 Database First,ASP.NET Core 1.0 EF Core操作数据库. Entity Frame ...

  2. ASP.Net Core 2.2 InProcess托管的Bug:unable to open database file

    最近把项目更新到了ASP.Net Core 2.2,发布之后发现在IIS下使用SQLite数据库不行了,报异常说不能打开数据库."unable to open database file&q ...

  3. [转]Using NLog for ASP.NET Core to write custom information to the database

    本文转自:https://github.com/NLog/NLog/issues/1366 In the previous versions of NLog it was easily possibl ...

  4. [转]Setting the NLog database connection string in the ASP.NET Core appsettings.json

    本文转自:https://damienbod.com/2016/09/22/setting-the-nlog-database-connection-string-in-the-asp-net-cor ...

  5. ASP.Net Core 2.2使用SQLite数据库unable to open database file

    原文:ASP.Net Core 2.2使用SQLite数据库unable to open database file 最近把项目更新到了ASP.Net Core 2.2,发布之后发现在IIS下使用SQ ...

  6. Asp.net Core中使用Session

    前言 2017年就这么悄无声息的开始了,2017年对我来说又是特别重要的一年. 元旦放假在家写了个Asp.net Core验证码登录, 做demo的过程中遇到两个小问题,第一是在Asp.net Cor ...

  7. TechEmpower 13轮测试中的ASP.NET Core性能测试

    应用性能直接影响到托管服务的成本,因此公司在开发应用时需要格外注意应用所使用的Web框架,初创公司尤其如此.此外,糟糕的应用性能也会影响到用户体验,甚至会因此受到相关搜索引擎的降级处罚.在选择框架时, ...

  8. ASP.NET Core 1.0 使用 Dapper 操作 MySql(包含事务)

    操作 MySql 数据库使用MySql.Data程序包(MySql 开发,其他第三方可能会有些问题). project.json 代码: { "version": "1. ...

  9. ASP.NET Core 1.0 开发记录

    官方资料: https://github.com/dotnet/core https://docs.microsoft.com/en-us/aspnet/core https://docs.micro ...

随机推荐

  1. wordpress 首页调用文章 不同样式的方法

    <?php $count = 1; $display_categories = array(1); foreach ($display_categories as $category) { ?& ...

  2. Ionic的跨域问题

    跨域大家都不陌生,但最近一直遇到一个坑,也是自身对ajax和angular的不深入造成,所以记录一笔,下次遇到绕过. 参考过:http://ionichina.com/topic/54f051698c ...

  3. 【初级】linux mkdir 命令详解及使用方法实战

    mkdir命令详解及使用方法实战 名称 MKDIR 是 make directories 的缩写 使用方法 mkdir [选项(如-p)] ...目录名称(及子目录注意用分隔符隔开)...    如使 ...

  4. Scala编程--基本类型和操作

    如果你熟悉Java,你会很开心地发现Java基本类型和操作符在Scala里有同样的意思.然而即使你是一位资深Java开发者,这里也仍然有一些有趣的差别使得本章值得一读.因为本章提到的一些Scala的方 ...

  5. 设置Windows 7 防火墙端口规则

    http://jingyan.baidu.com/article/c843ea0b7d5c7177931e4ab1.html?qq-pf-to=pcqq.c2c 主要解决手机访问pc站点的问题(pc和 ...

  6. Java在JFinal中出现Can not create instance of class: com.keesail.web.config.WebConfig异常处理方式

    编译的时候一直出现如下问题: 后面 查了许多资料 说是build项目的时候web.xml没有输出到class目录.后面试了很多方式不行.后面自己摸索出如下方式解决问题: 改成默认输出目录.

  7. c++ 中的sort用法

    别人写的,我拿来做做笔记 sort函数的用法 做ACM题的时候,排序是一种经常要用到的操作.如果每次都自己写个冒泡之类的O(n^2)排序,不但程序容易超时,而且浪费宝贵的比赛时间,还很有可能写错.ST ...

  8. 涵涵和爸爸习惯养成进度表(一)(May 5 - May 25)

    规则说明 三周时间(21天)内,没有哭脸,不超过三个无表情脸,可以给一个奖励(动画书等) 涵涵违反规则,在爸爸和妈妈都同意的情况下,可以给无表情脸 爸爸违反规则,在妈妈和涵涵都同意的情况下,可以给无表 ...

  9. 一些Layout的坑。坑死我自己了

    iOS这个东西,初学感觉,还好还好,然后一年之后再来修复一下初学的时候的代码,我只是感觉头很晕- - 别扶我. AutoLayout的坑,明明以前都没有的!!!升了iOS10就突然发现了这个坑,其实也 ...

  10. 大视野3562 [SHOI2014]神奇化合物

    http://www.lydsy.com/JudgeOnline/problem.php?id=3562 //Accepted 6020 kb 1012 ms //由于题目的特殊要求:然而,令科学家们 ...