.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
執行成功後實體類就創建完成了