.net core MVC中級教程(三)

一、對昨天主頁不能顯示添加的新成員信息bug進行修改
二、運用EFCore將其數據寫入數據庫中web

一、對昨天主頁不能顯示添加的新成員信息bug進行修改

修改下生命週期,在運行數據庫

Transient:每一次GetService都會建立一個新的實例json

Scoped:在同一個Scope內只初始化一個實例 ,能夠理解爲( 每個request級別只建立一個實例,同一個http request會在一個 scope內)多線程

Singleton:整個應用程序生命週期內只建立一個實例app

在這裏插入圖片描述
在這裏插入圖片描述
在這裏插入圖片描述
ok完成async

二、運用EFCore將其數據寫入數據庫中

咱們輸入的數據是要寫入數據庫裏面的,下面我將介紹怎麼鏈接數據庫,將數據寫入數據庫
第一步,添加鏈接數據庫的字符串 打開appsettings.jsonsvg

{
  "Logging": {
    "LogLevel": {
      "Default": "Warning"
    }
  },
  "AllowedHosts": "*",
  "ConnectionStrings": {
    "DefaultConnection": "Data Source=(localdb)\\ProjectsV13;Database=TutorialStudy;Trusted_connection=true;"
  } 
}

其中(localdb)\ProjectsV13注意看看本身的數據庫叫什麼?
在這裏插入圖片描述
而後創建Data文件夾,創建DataContext類,用來建立數據庫、表ui

using Microsoft.EntityFrameworkCore;
using TutorialStudy.Model;

namespace TutorialStudy.Data
{
    public class DataContext:DbContext
    {
        public DataContext(DbContextOptions<DataContext> options):base(options)
        {
            
        }

        public DbSet<Student> Students { get; set; }
    }
}

回到startup類進行註冊DataContext類,鏈接字符串this

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using TutorialStudy.Data;
using TutorialStudy.Model;
using TutorialStudy.Services;

namespace TutorialStudy
{
    public class Startup
    {
        private readonly IConfiguration _configuration;

        public Startup(IConfiguration configuration)
        {
            _configuration = configuration;
        }

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext<DataContext>(options =>
                {
                    options.UseSqlServer(_configuration.GetConnectionString("DefaultConnection"));
                });

            /*Transient:每一次GetService都會建立一個新的實例
                Scoped:在同一個Scope內只初始化一個實例 ,能夠理解爲( 每個request級別只建立一個實例,同一個http request會在一個 scope內)
                Singleton:整個應用程序生命週期內只建立一個實例 */

            //services.AddScoped<IRepository<Student>, InMemoryRepository>();
            services.AddSingleton<IRepository<Student>, InMemoryRepository>();
            services.AddMvc();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseStaticFiles();
            app.UseStatusCodePages();
            app.UseMvc(routes => { routes.MapRoute("Default", "{controller=Home}/{action=Index}/{id?}"); });


            app.Run(async (context) =>
            {
                await context.Response.WriteAsync("Hello World!");
            });
        }
    }
}

鏈接json字符串的爲GetConnectionString,能夠進入它源代碼看看spa

/// <summary>Shorthand for GetSection("ConnectionStrings")[name].</summary>
    /// <param name="configuration">The configuration.</param>
    /// <param name="name">The connection string key.</param>
    /// <returns></returns>
    public static string GetConnectionString(this IConfiguration configuration, string name)
    {
      return configuration?.GetSection("ConnectionStrings")?[name];
    }

意味着在appserttings.json文件中會找到ConnectionStrings裏面的下一級別也就是咱們所定義的DefaultConnection
或者這樣也行

var connectionString = _configuration["ConnectionStrings:DefaultConnection"];
            services.AddDbContext<DataContext>(options =>
            {
                    options.UseSqlServer(connectionString);
                    //options.UseSqlServer(_configuration.GetConnectionString("DefaultConnection"));
             });

更推薦第一種

接下來咱們把服務接口的實現類在從新寫一遍,在services中添加EfCoreRepository類

using System.Collections.Generic;
using System.Linq;
using TutorialStudy.Data;
using TutorialStudy.Model;

namespace TutorialStudy.Services
{
    public class EfCoreRepository:IRepository<Student>
    {
        private readonly DataContext _context;

        public EfCoreRepository(DataContext context)
        {
            _context = context;
        }

        public IEnumerable<Student> GetAll()
        {
            return _context.Students.ToList();
        }

        public Student GetById(int studentId)
        {
            return _context.Students.Find(studentId);
        }

        public Student Add(Student student)
        {
            //這裏就不須要maxId,由於在數據庫中Id屬性是自增的
            var model=new Student
            {
                FirstName = student.FirstName,
                LastName = student.LastName,
                BirthDate = student.BirthDate,
                Gender = student.Gender
            };
            _context.Students.Add(model);
            _context.SaveChanges();
            return student;
        }
    }
}

改下startup類中服務註冊與生命週期
在這裏插入圖片描述
//這裏不能用AddSingleton,會發生多線程的問題,這裏是每次http請求生成一個實例

在這裏插入圖片描述
打開這個
輸入這條語句add-migration initialDB,接着輸入這條語句update-database
在這裏插入圖片描述

噹噹噹!!!數據庫搞定
Add-Migration 將建立下一次基於上一次遷移以來的更改的遷移;
Update-Databse 將任何掛起的遷移應用到數據庫
接下來咱們運行下程序
在這裏插入圖片描述
主頁什麼都沒有是由於咱們數據庫是空的,還沒錄入數據
在這裏插入圖片描述

在這裏插入圖片描述
在這裏插入圖片描述
在這裏插入圖片描述
額,有一個問題是Id沒增加,然而當我關閉再次運行程序,過着點開他們的信息卻都有Id,這是一個小bug,
在這裏插入圖片描述
還有一個bug是當我在網頁刷新這一頁的時候發現會重複提交數據
在這裏插入圖片描述 第二個bug,下一篇解決吧

相關文章
相關標籤/搜索