ASP.NET Core MVC

本文详细介绍了如何在.NETCore6中使用EntityFrameworkCore(EFCore)通过DatabaseFirst和CoreFirst方法创建数据模型,包括添加NuGet包、配置连接字符串、动态配置、使用DI容器、处理证书问题以及在ASP.NETCoreMVC中集成和迁移数据库连接。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

使用 Core6.0 创建 EF Core

Database First 创建 EF Core (sql service)

  1. 添加NuGet 包的引用
    Microsoft.EntityFrameworkCore
    Microsoft.EntityFrameworkCore.Tools
    Microsoft.EntityFrameworkCore.Design
    Microsoft.EntityFrameworkCore.SqlServer
    Microsoft.EntityFrameworkCore.SqlServer.Design 已弃用

  2. 在程序包管理器控制台执行(工具-NuGet包管理器-程序包管理器控制台)
    Scaffold-DbContext "Server=.;User Id=sa;Password=123456;Database=HaircutDB;Persist Security Info=True;" Microsoft.EntityFrameworkCore.SqlServer -o Models -f

在这里插入图片描述
在这里插入图片描述

成功创建完成后会自动创建上下文类及模型类
在这里插入图片描述

  1. 连接串动态配置
    自动创建模型时会在上下文类里创建一条链接数据库的字符串 上文中的黄色提醒 就是因为 该字符串不能存在上下文类中
  • 将数据上下文中固定连接串去掉
    请添加图片描述

  • 在appsettings.json中重新配置链接字符串

  //链接sql service数据库
  "ConnectionStrings": {
    "SqlServerConnection": "Server=.;User Id=sa;Password=123456;Database=HaircutDB;Persist Security Info=True;"
  },

请添加图片描述获取到自定义配置的节点的配置

//通过配置文件获取信息
var con1 = builder.Configuration["msghello"];
Console.WriteLine("第一种方法读取配置文件信息:" + con1);
//2.
var con2 = builder.Configuration.GetValue<string>("msghello");
Console.WriteLine("第二种方法读取配置文件信息:" + con2);
  1. 配置服务器的DI容器
    获取到刚刚配置的链接字符串 在入口函数文件去获取链接并且通过DI注册配置上下文类
//获取链接字符串
var conn = builder.Configuration.GetConnectionString("conn");
//配置服务器的DI[依赖注入](配置上下文类)
builder.Services.AddDbContext<HaircutDBContext>(options => options.UseSqlServer(conn));
//输出打印
Console.WriteLine(conn);

请添加图片描述5. 配置完成,可以进行使用

错误

在这里插入图片描述

使用时如果出现证书问题 可以直接信任 或者 链接字符串 后面添加Encrypt=false
在这里插入图片描述
请添加图片描述Scaffold-DbContext "Server=.;User Id=sa;Password=123456;Database=HaircutDB;Persist Security Info=True;Encrypt=false"Microsoft.EntityFrameworkCore.SqlServer -o Models -f

Core First 创建 EF Core

  1. 导入NuGet包
    使用命令行直接导入包(-version 6.0.25 需要安装的版本[与core的版本要相符])
    Install-Package Microsoft.EntityFrameworkCore -version 6.0.25
    Install-Package Microsoft.EntityFrameworkCore.SqlServer -version 6.0.25
    Install-Package Microsoft.EntityFrameworkCore.Tools -version 6.0.25

  2. 创建模型类及上下文类(配置映射关系)

请添加图片描述请添加图片描述

//模型类
	public class UserInfo
	{
		[Key]
		public int uid { get; set; }
		public string uname { get; set; } = null!;
		public bool ustate { get; set; }
	}

//上下文类
public class UsersContext : DbContext
	{
		public UsersContext(DbContextOptions<UsersContext> options) : base(options)
		{
		}

		public virtual DbSet<UserInfo> UsersInfo { get; set; } = null!;
	}

  1. appsettings.json配置数据库链接字符串

请添加图片描述


  "ConnectionStrings": {
    "sqlcon": "Server=.;User Id=sa;Password=123456;Database=UserDB;Persist Security Info=True;"
  }
  1. Program.cs将上下文类注册服务(并使用相关数据库中间件)

请添加图片描述

builder.Services.AddDbContext<UsersContext>(options =>
options.UseSqlServer(builder.Configuration.GetConnectionString("sqlcon")));

使用ASP.NET Core MVC 案例

mvc layui表格绑定为例子 (几乎操作无区别)

后端代码:

 //通过依赖注入 构建 上下文类
public readonly HaircutDBContext db;
public SysController(HaircutDBContext context)
{
    db = context;
}

//进行查找列表
public IActionResult GetList(int page, int limit, string SelName = "")
{
    //var ptlist = (from p in db.UserInfos
    //select p).ToList();
    List<UserInfo> ptlist = db.UserInfos.ToList();
    //模糊查询
    if (!string.IsNullOrEmpty(SelName))
    {
    ptlist = ptlist.Where(p => p.Uname.Contains(SelName)).ToList();
    }

    //layui表格展示
    var pjson = new
    {
        code = 0,
        msg = "",
        count = ptlist.Count,
        //分页
        data = ptlist.OrderByDescending(p => p.URegTime).Skip((page - 1) * limit).Take(limit).ToList()
    };
    return Json(pjson);//返回匿名类型
}

前端代码:

// 创建渲染实例
table.render({
	elem: '#test',
	id: 'test',
	url: '/Sys/GetList',
	height: 'full-35', // 最大高度减去其他容器已占有的高度差
	page: true,// 是否显示分页
	limits: [5, 10, 15],
	limit: 5, // 每页默认显示的数量
	cols: [[
		{ type: 'checkbox', fixed: 'left', align: 'center' },
		{ field: 'uId', fixed: 'left', title: 'ID', sort: true, align: 'center' },
		{ field: 'uname', title: '名称', align: 'center' },
		{ field: 'uPhone', title: '联系', align: 'center' },
		{ fixed: 'right', title: '操作', align: 'center' }
	]]
});

创建其他数据库的链接

  1. 使用nuget添加引用
	//mysql数据库	
	Microsoft.EntityFrameworkCore.Design	
	Microsoft.EntityFrameworkCore.Tools	
  Pomelo.EntityFrameworkCore.MySql	
			
	//oracle数据库	
	Microsoft.EntityFrameworkCore.Tools	
	Oracle.EntityFrameworkCore	
	Oracle.ManagedDataAccess.Core	
  1. 在程序包管理器控制台执行语句
//mysql	
Scaffold-DbContext "server=localhost;userid=root;pwd=03047237;port=3306;database=userinfo;sslmode=none;" Pomelo.EntityFrameworkCore.MySql -OutputDir Models -Force	
			
//oracle	
Scaffold-DbContext "Data Source=(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=127.0.0.1)(PORT=1521))(CONNECT_DATA=(SERVER=DEDICATED)(SERVICE_NAME=orcl)));User Id=zzz;Password=123456;" Oracle.EntityFrameworkCore -O  Models  -F	
	要选中默认项目	
	-o 后面指定文件夹,	
	-f 表示是否覆盖原文件	
	-t 后面跟表名	
  1. 连接串动态配置
    a、将数据上下文中固定连接串去掉
    b、appsettings.json中配置链接串
	//mysql数据库配置	
	"ConnectionStrings": {	
		    "MySqlConnection": "server=localhost;userid=root;pwd=123456;port=3306;database=School;sslmode=none"	
		  }	
			
	//oracle数据库配置	
	"ConnectionStrings": {
    "OracleConnection": "Data Source=(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=127.0.0.1)(PORT=1521))(CONNECT_DATA=				(SERVER=DEDICATED)(SERVICE_NAME=orcl)));User Id=zzz;Password=123456;"
  }
			
  1. 注册服务 在Program.cs
//mysql服务	
builder.Services.AddDbContext<SchoolContext>(options =>
		options.UseMySql(Configuration.GetConnectionString("MySqlConnection"),MySqlServerVersion.LatestSupportedServerVersion));	
			
//oracle服务	

builder.Services.AddDbContext<ModelContext>(options =>
                options.UseOracle(Configuration.GetConnectionString(""OracleConnection"")));

常用中间件使用

session

  1. 配置引用中间件 Program.cs
//注册session
builder.Services.AddSession();

//使用中间件
app.UseSession();
  1. 在后台使用(存储session值)
    需要序列化成字符串形式(JsonConvert 需要导入NuGet包)
    请添加图片描述
//使用session 存储 
HttpContext.Session.SetString("list", JsonConvert.SerializeObject(list));

//使用session 获取
List<Access> a = JsonConvert.DeserializeObject<List<Access>>(HttpContext.Session.GetString("list"));

后台使用session可以直接GetString获取

  1. 在前台使用(获取session值)
    请添加图片描述
@*获取session 引用命名空间 反序列化json*@
@using Microsoft.AspNetCore.Http;
@using Newtonsoft.Json;
@{
	List<Access>? a = JsonConvert.DeserializeObject<List<Access>>(base.Context.Session.GetString("list"));
}
"Learning ASP.NET Core MVC Programming" English | ISBN: 1786463830 | 2016 | EPUB | 342 pages | 17 MB Key Features Get a first-principles coverage of ASP.NET MVC and the latest release, Core This book is uniquely designed for developers who are looking to transition their skills into the .NET development field The standalone chapter structure leaves you free to explore ASP.NET MVC to immediately solve your pain points Book Description ASP.NET Core MVC helps you build robust web applications using the Model-View-Controller design. This guide will help you in building applications which can be deployed on non-windows platforms such as Linux. In today's age, it is crucial that you possess the ability to separate the programming and business logic, and this is exactly what ASP.NET Core MVC application will help you achieve. This version comes with a number of improvements that enable fast, TDD-friendly development to create sophisticated applications. You would also learn the fundamentals of Entity framework and on how to use the same in ASP.NET Core web applications. The book presents the fundamentals and philosophies of ASP.NET Core. Starting with an overview of the MVC pattern, we quickly dive into the aspects that you need to know to get started with ASP.NET. You will learn about the core architecture of model, view, and control. Integrating your application with Bootstrap, validating user input, interacting with databases, and deploying your application are some of the things that you will be able to execute with this fast-paced guide. The end of the book will test your knowledge as you build a fully working sample application using the skills you've learned throughout the book. What you will learn Get to know the concepts of ASP.NET MVC and build a new static web page using HTML, CSS, and jQuery Set up a development environment and run a sample application using the template Create a Controller with action methods Build a view using several features of the Razor View engine Construct a Model for ASP.NET Core MVC application Devise a custom mechanism to provide maximum flexibility to your application through routing Validate the user input on the client side using jQuery Enhance your applications using Bootstrap Explore new configuration and deployment scenarios—step by step guide to deploying ASP.NET Core web application in Linux
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值