ASP.NET Core (Database First)


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

 

來看看效果

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM