ASP.NET CORE 连接 SQL SERVER2008R2 数据库

ASP.NET CORE 连接 SQL SERVER

1.新建asp.net项目,我用的是VS 2017
ASP.NET CORE 连接 SQL SERVER2008R2 数据库_第1张图片
ASP.NET CORE 连接 SQL SERVER2008R2 数据库_第2张图片
ASP.NET CORE 连接 SQL SERVER2008R2 数据库_第3张图片
2.打开如图控制台,输入命令:Scaffold-DbContext “Data Source=127.0.0.1;Initial Catalog=Spring_MVC_Core;User ID=sa;Password=*******;MultipleActiveResultSets=true;” Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models 回车,参数分别为数据库地址、名字、管理员账号、密码
ASP.NET CORE 连接 SQL SERVER2008R2 数据库_第4张图片
3.会根据你的数据库名称自动生成一个Context.cs文件,右键 controllers 文件夹,然后选择控制器,选择视图控制器,在新窗口选择用户模型,添加
ASP.NET CORE 连接 SQL SERVER2008R2 数据库_第5张图片
ASP.NET CORE 连接 SQL SERVER2008R2 数据库_第6张图片
ASP.NET CORE 连接 SQL SERVER2008R2 数据库_第7张图片
4.程序会自动创建user控制器和视图
ASP.NET CORE 连接 SQL SERVER2008R2 数据库_第8张图片
5.打开Models,Spring_MVC_CoreContext.cs文件,注释掉如下内容

using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata;

namespace TestCore.Models
{
    public partial class Spring_MVC_CoreContext : DbContext
    {
        public Spring_MVC_CoreContext()
        {
        }

        public Spring_MVC_CoreContext(DbContextOptions options)
            : base(options)
        {
        }

        public virtual DbSet Users { get; set; }

        //protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        //{
        //    if (!optionsBuilder.IsConfigured)
        //    {
        //        #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=127.0.0.1;Initial Catalog=Spring_MVC_Core;User ID=sa;Password=654321;MultipleActiveResultSets=true;");
        //    }
        //}

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity(entity =>
            {
                entity.ToTable("users");

                entity.Property(e => e.Id)
                    .HasColumnName("id")
                    .ValueGeneratedNever();

                entity.Property(e => e.Account)
                    .IsRequired()
                    .HasColumnName("account")
                    .HasMaxLength(50);

                entity.Property(e => e.Email)
                    .HasColumnName("email")
                    .HasMaxLength(50);

                entity.Property(e => e.Name)
                    .IsRequired()
                    .HasColumnName("name")
                    .HasMaxLength(50);

                entity.Property(e => e.Password)
                    .IsRequired()
                    .HasColumnName("password")
                    .HasMaxLength(50);

                entity.Property(e => e.Phone)
                    .HasColumnName("phone")
                    .HasMaxLength(50);

                entity.Property(e => e.Rights)
                    .IsRequired()
                    .HasColumnName("rights")
                    .HasMaxLength(50);
            });
        }
    }
}

6.打开appsettings.json文件,添加数据库连接,如下

{
  "Logging": {
    "LogLevel": {
      "Default": "Warning"
    }
  },
  "AllowedHosts": "*",

  "ConnectionStrings": {
    // 新加入的内容:数据库地址       数据库名       帐号          密码
    "DefaultConnection": "Server=localhost;Database=Spring_MVC_Core;User ID=sa;Password=******;"
  }
}

7.打开startup.cs,加入数据库服务

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using TestCore.Models;

namespace TestCore
{
    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.Configure(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });
			//下面为加入的数据库服务,注意Spring_MVC_CoreContext修改为自己的文件名
            services.AddDbContext(options =>
                options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

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

        // 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();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                app.UseHsts();
            }

            app.UseHttpsRedirection();
            app.UseStaticFiles();
            app.UseCookiePolicy();

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    //我将users设为默认启动了,程序打开后可以看见users数据
                    template: "{controller=Users}/{action=Index}/{id?}");
            });
        }
    }
}

8.可以将users设为默认启动,或者在views/shared/_layout.cshtml内加入users链接,如下


9.最终效果如图
ASP.NET CORE 连接 SQL SERVER2008R2 数据库_第9张图片

你可能感兴趣的:(asp.net,core,asp.net,springmvc,core,sql,server)