ASP.NET Core中SqlSugar基本使用

时间:2025-04-20 07:25:05

创建数据模型

 public class News
 {
     [SugarColumn(IsIdentity = true, IsPrimaryKey = true)]
     public int Id { get; set; }
     //nvarchar带中文比较好
     [SugarColumn(ColumnDataType = "nvarchar(30)")]
     public string Title { get; set; }
     [SugarColumn(ColumnDataType = "text")]
     public string Content { get; set; }
     public DateTime Time { get; set; }
     public int BrowseCount { get; set; }
     public int LikeCount { get; set; }
 ​
     public int TypeId { get; set; }
     public int WriterId { get; set; }
     /// <summary>
     /// 类型,不映射到数据库
     /// </summary>
     [SugarColumn(IsIgnore = true)]
     public TypeInfo TypeInfo { get; set; }
 ​
 ​
 }

注册依赖

 //注册上下文:AOP里面可以获取IOC对象,如果有现成框架比如Furion可以不写这一行
 builder.Services.AddHttpContextAccessor();
 //注册SqlSugar用AddScoped
 builder.Services.AddScoped<ISqlSugarClient>(s =>
 {
     //Scoped用SqlSugarClient 
     SqlSugarClient sqlSugar = new SqlSugarClient(new ConnectionConfig()
     {
         DbType = SqlSugar.DbType.SqlServer,
         ConnectionString = "Server=LAPTOP-F352TNCB\\SQLEXPRESS;Database=MyTestDB;Trusted_Connection=True;Encrypt=True;TrustServerCertificate=True;",
         IsAutoCloseConnection = true,
     });
     return sqlSugar;
 });

创建表

 private readonly ISqlSugarClient db;
 ​
 public GetString(ISqlSugarClient db)
 {
     this.db = db;
 ​
     db.DbMaintenance.CreateDatabase();//达梦和Oracle不支持建库
 ​
     //建表(看文档迁移)
     db.CodeFirst.InitTables<News>(); //所有库都支持    
 ​
 ​
 ​
 }

增删改查

 public List<News> Get()
 {
     //查询表的所有
     var list = db.Queryable<News>().ToList();
     return list;
 }
 ​
 public bool Add()
 {
     int result=db.Insertable(new News() { Id=1,Title="hhh",Content="dfafasaf" }).ExecuteCommand();
     if (result != 0)
     {
         return true;
     }
     else
     {
         return false;
     }
 }
 ​
 public bool Update()
 {
     int result = db.Updateable(new News() { Id = 2, Title = "qqq", Content = "1111111" }).ExecuteCommand();
     if (result != 0)
     {
         return true;
     }
     else
     {
         return false;
     }
 }
 ​
 public bool Delete()
 {
     int result = db.Deleteable<News>().Where(it => it.Id == 2).ExecuteCommand();
     if (result != 0)
     {
         return true;
     }
     else
     {
         return false;
     }

详情看官方文档