.net core 连接数据库
什么是.net core
我们知道操作系统不止有Windows,还有Mac和Linux等等, .NET的实现 如果按操作系统来横向分割的话,可以分为 Windows系统下的 .NET Framework 和 兼容多个操作系统的 .NET Core。
为什么要使用.net core
我们都知道.NET Core是一个可以用来构建现代、可伸缩和高性能的跨平台软件应用程序的通用开发框架。可用于为Windows、Linux和MacOS构建软件应用程序。与其他软件框架不同,.NET Core是最通用的框架,可用于构建各种软件,包括Web应用程序、移动应用程序、桌面应用程序、云服务、微服务、API、游戏和物联网应用程序。与其他框架不同,.NET Core并不局限於单一的编程语言,它支持C#、VB.NET、F#、XAML和TypeScript。这些编程语言都是开源的,由独立的社区管理。
准备工作
开发工具 visual studio 2019
第一步创建一个项目
右击项目
下载以下三个程序包
准备工作就完成了
如何与数据库连接
右键models创建一个类命名喂dbcontext
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace xxx.Models
{
public class dbcontext:DbContext
{
public dbcontext(DbContextOptions<dbcontext> options) : base(options)
{
}
public DbSet<books> books { get; set; }
public DbSet<Booktypes> Booktypes { get; set; }
}
}
之后创建两个类,类名和表面一致
books表
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace xxx.Models
{
public class books
{
public int ID { get; set; }
public string Name { get; set; }
public string Remark { get; set; }
public int TypeID { get; set; }
public string TypeName { get; set; }
public int cs { get; set; }
}
}
Booktypes表
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace xxx.Models
{
public class Booktypes
{
public int ID { get; set; }
public string Name { get; set; }
public int Nums { get; set; }
}
}
之后进入Startup.cs 和appsetting.json设置配置文件
public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews();
services.AddDbContext<dbc>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
}
进入
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"AllowedHosts": "*",
//连接字符串
"ConnectionStrings": {
"DefaultConnection": "Server=LAPTOP-41UVLMDC\\Shalltear;Database=EnRole_DB;Trusted_Connection=True;MultipleActiveResultSets=true"
}
}
之后进入
输入格式
这里是引用了我的好兄弟https://blog.csdn.net/qq_40052237
比如
Scaffold-DbContext -Force "Server=LAPTOP-41UVLMDC\Shalltear;Database=EnRole_DB;uid=pzh;Password=123;" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models/DataModels
执行成功后实体类就创建完成了