官网: https://www.donet5.com/home/doc
unget: SqlSugarCore
1.整体目录结果
2. DbContext.cs文件内容
using SqlSugar; using System.Diagnostics; using System.Reflection; using WEBAPI.Model.Entitys; namespace WEBAPI.Commonn { public class DbContext { public static SqlSugarClient db = new SqlSugarClient(new ConnectionConfig() { ConnectionString = "server=.;database=WebApiOne1;uid=sa;pwd=123456;", //链接字符 DbType = DbType.SqlServer, //设置数据库类型 IsAutoCloseConnection = true, // 不设置为true要手动 关闭close }); public static void InitDataBase() { //初始化数据库,如果不存在则创建数据库 db.DbMaintenance.CreateDatabase(); //创建表 string nspace = "WEBAPI.Model.Entitys"; Type[] ass = Assembly.LoadFrom(@"bin/Debug/net8.0/WEBAPI.Model.dll").GetTypes().Where(p => p.Namespace == nspace).ToArray(); db.CodeFirst.InitTables(ass); //写入测试数据 List<Users> list = new List<Users>() { new Users() { NickName="账号名1231", Password="123456", UserType=3, UserName="名字", CreatedDate=DateTime.Now, }, new Users() { NickName="账号名1131", Password="1234567", UserType=4, UserName="名字1", CreatedDate=DateTime.Now, }, new Users() { NickName="账号名2131", Password="12345678", UserType=1, UserName="名字2", CreatedDate=DateTime.Now, } }; db.Insertable(list).ExecuteCommand(); } } }
3.Users.cs文件内容
using Dm; using Microsoft.VisualBasic; using SqlSugar; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace WEBAPI.Model.Entitys { public class Users { //IsPrimaryKey 是否为主键 //IsIdentity 是否自增 //IsNullable 是否为空 //ColumnDataType 设置数据类型 //DefaultValue 设置默认值 [SugarColumn(IsPrimaryKey = true, IsIdentity = true)] public long Id { get; set; } [SugarColumn(IsNullable = false)] public string NickName { get; set; } [SugarColumn(IsNullable = false)] public string Password { get; set; } [SugarColumn(ColumnDataType = "datetime",DefaultValue = "getdate()")] // 设置列的数据类型为 datetime public DateTime CreatedDate { get; set; } [SugarColumn(IsNullable = false)] public int UserType { get; set; } [SugarColumn(IsNullable = false)] public string UserName { get; set; } } }
4. 在 WEBAPI.Commonn 依赖项中添加 WEBAPI.Model ,否则 Assembly.LoadFrom(@"bin/Debug/net8.0/WEBAPI.Model.dll") 会报错找不到文件路径
5.调用 DbContext.cs 文件下的 InitDataBase方法就可以了
标签:WEBAPI,set,入门,get,System,使用,using,public,SqlSugar From: https://www.cnblogs.com/tlfe/p/18224142