iT邦幫忙

2022 iThome 鐵人賽

DAY 3
0
IT管理

Azure開發者必備掌握的基本系列 第 3

Azure開發者必備掌握的基本_第03天_專案搭配DB的應用準備

  • 分享至 

  • xImage
  •  

使用vs2019搭配3.1 LTS .net core版本 (5.0微軟好像已經沒有開放在azure平台上)

新增一個.net core 3.1 mvc專案
https://ithelp.ithome.com.tw/upload/images/20220915/20107452VP69hwrt8d.png

https://ithelp.ithome.com.tw/upload/images/20220915/20107452hIYukmyi3q.png

於同方案中新增一個 C#類別庫專案
https://ithelp.ithome.com.tw/upload/images/20220915/20107452eXJCIB1zfV.png

https://ithelp.ithome.com.tw/upload/images/20220915/20107452H0DU4dUcja.png

https://ithelp.ithome.com.tw/upload/images/20220915/20107452S1OgLcPn28.png

https://ithelp.ithome.com.tw/upload/images/20220915/20107452K7t552q6fu.png

安裝EFcore Power Tool
https://marketplace.visualstudio.com/items?itemName=ErikEJ.EFCorePowerTools

https://ithelp.ithome.com.tw/upload/images/20220915/201074529UW4hjTj7g.png

要先將visual studio關閉

https://ithelp.ithome.com.tw/upload/images/20220915/20107452yka8Krpxd5.png

安裝好後重啟vs2019剛建方案
預設自動生的Class1刪除
https://ithelp.ithome.com.tw/upload/images/20220915/20107452gcGskk1Kiv.png

https://ithelp.ithome.com.tw/upload/images/20220915/201074527O6lKZqQgA.png

https://ithelp.ithome.com.tw/upload/images/20220915/20107452tG3QLvM6Lf.png

在此我隨意挑一個本地有的資料庫(剛好有User測試資料)

https://ithelp.ithome.com.tw/upload/images/20220915/20107452hmC2WYv9vr.png

https://ithelp.ithome.com.tw/upload/images/20220915/20107452tci4Eh1Thb.png

https://ithelp.ithome.com.tw/upload/images/20220915/201074527JGdNo1Ytj.png

https://ithelp.ithome.com.tw/upload/images/20220915/20107452jUGzsv9HLp.png

在此進行table選取產生DbContext和Entity Class
https://ithelp.ithome.com.tw/upload/images/20220915/20107452WwDZWPH48L.png

https://ithelp.ithome.com.tw/upload/images/20220915/20107452fNTAjN4VbJ.png

https://ithelp.ithome.com.tw/upload/images/20220915/20107452ToSz09VY6R.png

nuget套件補安裝efcore

https://ithelp.ithome.com.tw/upload/images/20220915/20107452sL02PlrFt8.png

https://ithelp.ithome.com.tw/upload/images/20220915/20107452Bk1cOIF5UF.png

將Class Library建置完成後就可添加專案參考到.net core mvc專案中
https://ithelp.ithome.com.tw/upload/images/20220915/20107452B5t9g5iI9p.png

https://ithelp.ithome.com.tw/upload/images/20220915/201074525qgORiN6Zd.png

https://ithelp.ithome.com.tw/upload/images/20220915/20107452Ld0F9BHSV4.png

創建efcore controller
這裡可能會報錯就重新添加相應nuget套建在mvc專案即可
https://ithelp.ithome.com.tw/upload/images/20220915/20107452Jx8HaG8AvM.png

https://ithelp.ithome.com.tw/upload/images/20220915/20107452m9EtXedltm.png

https://ithelp.ithome.com.tw/upload/images/20220915/20107452dm3994OYsM.png

https://ithelp.ithome.com.tw/upload/images/20220915/20107452ZOhL9xJy6S.png

改用創建空白控制器
https://ithelp.ithome.com.tw/upload/images/20220915/20107452UgM0wfj3Bt.png

https://ithelp.ithome.com.tw/upload/images/20220915/201074523KoC1uJ1Id.png

新增View
https://ithelp.ithome.com.tw/upload/images/20220915/2010745244UAbFdcVw.png

https://ithelp.ithome.com.tw/upload/images/20220915/20107452oRNXTuUyZM.png

預設Scaffold模板生成

@model IEnumerable<DAL.User>

@{
    ViewData["Title"] = "Index";
}

<h1>Index</h1>

<p>
    <a asp-action="Create">Create New</a>
</p>
<table class="table">
    <thead>
        <tr>
            <th>
                @Html.DisplayNameFor(model => model.UserId)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.UserRoleId)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.UserAccount)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.UserPassword)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.UserEmail)
            </th>
            <th></th>
        </tr>
    </thead>
    <tbody>
@foreach (var item in Model) {
        <tr>
            <td>
                @Html.DisplayFor(modelItem => item.UserId)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.UserRoleId)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.UserAccount)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.UserPassword)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.UserEmail)
            </td>
            <td>
                @Html.ActionLink("Edit", "Edit", new { /* id=item.PrimaryKey */ }) |
                @Html.ActionLink("Details", "Details", new { /* id=item.PrimaryKey */ }) |
                @Html.ActionLink("Delete", "Delete", new { /* id=item.PrimaryKey */ })
            </td>
        </tr>
}
    </tbody>
</table>


~\WebAppMVC\appsettings.json
設定連接字串

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*",
  "ConnectionStrings": {
    "DbConnection": "Server=.;Database=IT_Db;uid=xxx;pwd=xxxxxxx"
  }
}

再到Startup.cs進行DB服務註冊

using DAL;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace WebAppMVC
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
**            services.AddDbContext<IT_DbContext>(options =>
                options.UseSqlServer(Configuration.GetConnectionString("DbConnection")));**

            services.AddControllersWithViews();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }
            app.UseStaticFiles();

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Users}/{action=Index}/{id?}");
            });
        }
    }
}

再到控制器做DI存取Users回傳到View
就有一個簡易DB小網站
https://ithelp.ithome.com.tw/upload/images/20220915/20107452qU5sWfmDeF.png

下回要介紹Azure DB部分操作
與站台佈署測試


上一篇
Azure開發者必備掌握的基本_第02天_App Service_WebApp
下一篇
Azure開發者必備掌握的基本_第04天_專案搭配DB的應用準備(二)
系列文
Azure開發者必備掌握的基本30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言