我们一起来学习Asp.NET Core MVC 第一篇 Core MVC连接Sqlserver数据库


       前言  Asp.Net Core是基于Framwork4.X,与早期 MVC相比,Core 云服务支持更好,一个Core工程项目既包含WebAPI,同时也可以包含MVC的Webs发布。

第一篇   通过Microsoft Visual Studio(本案例版本:2019)快速创建Core MVC连接Sqlserver数据库

 

       说明:本篇blog简单介绍Asp.Net Core快速创建Sqlserver数据库的CRUD(添加、删除、查找、修改)的基本案例,重点介绍Core MVC入门实操,仅做参考!大侠绕步?

       学习目标

       1、初步了解Core平台MVC(模型-控制器-视图)框架结构;

       2、掌握使用Vs2019 IDE工具快速搭建Core项目;

       3、学习Core MVC配置、Sql配置以及注册服务等方法;

      前期准备:安装Vs2017以上版本(集成Core SDK环境),安装Sqlserver2008(含)以上版本的数据库。

     一、创建项目

      为了快速搭建MVC项目我们默认选择带有(模型-视图-控制器)的.Net Core Webs项目。。

        

        继续下一步,项目名称输入MVC_SQL_Test  

        

       继续下一步,Core默认版本选择3.1

       

        说明:Core 标准的MVC目录结构与之早期MVC类似,主要由Models(模型)、Controllers(控制器)、VIews(视图)三层架构组成,Startup.cs主要用来注册服务。

                    另外,Core MVC与以往的最大的区别是支持跨平台,及以包(Docker)的方式发布Linux平台。

        

      二、导入Sqlserver中间件程序包

        右键选择项目资源,点击NuGet程序包,选择“Microsoft.EntityFrameworkCore.SqlServer”(V3.0)和“Microsoft.EntityFrameworkCore.Tool”(V3.0)以及:"EntityFramework.SqlServerCompact" (V4.1)

       三、创建Sqlserver连接

       点击菜单栏【视图】->【其它窗口】->【程序包管理台控制器】,输入以下命令由Vs自动创建。

        Scaffold-DbContext “Data Source=127.0.0.1;Initial Catalog=InfoUser;User ID=sa;Password=sa;MultipleActiveResultSets=true;” Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models

       

     四、创建Sqlserver数据库

          在Sqlserver中创建数据库名称为InfoData,数据表为UserData,三个字段分别为:UserId,UserName和Password。

    五、创建控制器视图

          右键选择资源管理器【Controllers】->添加【控制器】->选择【视图使用Entity Framework的MVC控制器】

          此处注意:很多朋友创建Controllers时会报错提示model缺少“primary key”,即自动关联的数据库缺少主键;

 这时需要在Models中的UserData.cs类中添加主键[key],如下图所示:

        通过Vs2019工具手动创建控制器:右键点击"Controllers",添加“控制器”,在打开的窗口中选择“Entity Framework的MVC控制器”,

  六、注册服务和路由

          1、在appsettings.json文件中配置Sqlserver连接信息。

"Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*",
  "ConnectionStrings": {
    "MVCSqlContext": "Server=localhost;Database=InfoUser;User ID=sa;Password=sa;"
  }
}

        2、在InfoUserContenxt.cs中注释掉以下代码

         3、在Startups文件中加入下面的代码

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
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;
using Microsoft.EntityFrameworkCore;
using MVC_SQL_Test.Models;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

namespace MVC_SQL_Test
{
    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.AddControllersWithViews();
            //下面为加入的数据库服务,注意MVCSqlContext修改为自己的文件名
            services.AddDbContext(options =>
            //services.AddDbContext(options =>
                    options.UseSqlServer(Configuration.GetConnectionString("MVCSqlContext")));



            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_3_0);
        }

        // 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");
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }
            app.UseHttpsRedirection();
            app.UseStaticFiles();

            app.UseRouting();

            app.UseAuthorization();

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

  接着将Startup.cs文件中 pattern: "{controller=Home}/{action=Index}/{id?}");语句中Home改为用户页,即pattern: "{controller=UserDatas}/{action=Index}/{id?}");项目重新生成后运

 

 

 

相关