ASP.NET Core (Database First)

时间:2021-08-30 23:37:45
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

添加 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)