ASP.NET CORE 连接 SQL SERVER2008R2 数据库 - Go语言中文社区

ASP.NET CORE 连接 SQL SERVER2008R2 数据库


ASP.NET CORE 连接 SQL SERVER

1.新建asp.net项目,我用的是VS 2017
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
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 回车,参数分别为数据库地址、名字、管理员账号、密码
在这里插入图片描述
3.会根据你的数据库名称自动生成一个Context.cs文件,右键 controllers 文件夹,然后选择控制器,选择视图控制器,在新窗口选择用户模型,添加
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
4.程序会自动创建user控制器和视图
在这里插入图片描述
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<Spring_MVC_CoreContext> options)
            : base(options)
        {
        }

        public virtual DbSet<Users> 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<Users>(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<CookiePolicyOptions>(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<Spring_MVC_CoreContext>(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链接,如下

<ul class="nav navbar-nav">
    <li><a asp-area="" asp-controller="Home" asp-action="Index">Home</a></li>
    <li><a asp-area="" asp-controller="Home" asp-action="About">About</a></li>
   <li><a asp-area="" asp-controller="Home" asp-action="Contact">Contact</a></li>
   <li><a asp-area="" asp-controller="Users" asp-action="Index">Users</a></li>
</ul>

9.最终效果如图
在这里插入图片描述

版权声明:本文来源CSDN,感谢博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
原文链接:https://blog.csdn.net/weixin_42176639/article/details/99410914
站方申明:本站部分内容来自社区用户分享,若涉及侵权,请联系站方删除。
  • 发表于 2020-06-27 22:59:26
  • 阅读 ( 1381 )
  • 分类:数据库

0 条评论

请先 登录 后评论

官方社群

GO教程

猜你喜欢