一、安装
第一步,在你的项目中找到解决方案,右键-管理解决方案的Nuget
第二步,下载对应的包,注意你的框架是哪个就下载哪个的包,一个项目安装一次包即可
点击应用和确定
安装好后会显示sqlsugar的包
二、使用:增删改查
using SqlSugar;
using SqlSugar;
using System.Diagnostics.CodeAnalysis;
using System.Reflection;
[SugarTable("TestTable")] // 指定实体类对应的数据库表名
class TestTable
{
[SugarColumn(IsPrimaryKey = true)] // 指定主键列
public string Id { get; set; }
public string Name { get; set; }
public int Age { get; set; }
public string Content { get; set; }
public int IsEnable { get; set; }
public int IsDeleted { get; set; }
public string Stage { get; set; }
public string Remarks { get; set; }
}
class Test
{
public static int AddOrUpdate<T>(SqlSugarClient db,T entity) where T : class, new()
{
var entityIdProp = GetEntityIdProperty<T>();
var entityIdValue = entityIdProp.GetValue(entity);
var dbEntity = db.Queryable<T>().InSingle(entityIdValue);
if (dbEntity != null)
{
// 根据 ID 查询到了记录,执行更新操作
return db.Updateable(entity).ExecuteCommand();
}
else
{
// 根据 ID 没有查询到记录,执行插入操作
return db.Insertable(entity).ExecuteCommand();
}
}
public static PropertyInfo GetEntityIdProperty<T>() where T : class, new()
{
var entityType = typeof(T);
var properties = entityType.GetProperties();
foreach (var property in properties)
{
var attribute = Attribute.GetCustomAttribute(property, typeof(SqlSugar.SugarColumn)) as SqlSugar.SugarColumn;
if (attribute != null && attribute.IsPrimaryKey)
{
return property;
}
}
throw new Exception($"实体类型 {entityType.FullName} 没有定义主键");
}
static void Main(string[] args)
{
// 创建 SqlSugar 实例
SqlSugarClient db = new SqlSugarClient(new ConnectionConfig()
{
ConnectionString = "server = DESKTOP-FTH2P3S; Database = TestDb; Trusted_Connection = SSPI;", // 数据库连接字符串
DbType = DbType.SqlServer, // 数据库类型
IsAutoCloseConnection = true, // 是否自动关闭数据库连接
});
// 1.插入数据
var model = new TestTable()
{
Id = Guid.NewGuid().ToString(),
Name = "Tom",
Age = 18,
Content = "Hello World",
IsEnable = 1,
IsDeleted = 0,
Stage = "Stage 1",
Remarks = "Test"
};
int insert_code = db.Insertable(model).ExecuteCommand();//返回影响行数
// 2.查询数据
var list = db.Queryable<TestTable>().ToList();
// 3.自定义查询SQL
var result = db.SqlQueryable<TestTable>("SELECT * FROM TestTable WHERE Age > 30").ToList();
// 4.更新数据
var updateModel = db.Queryable<TestTable>().Where(it => it.Id == "8ffd64fc-8aea-4641-a57b-d957ad0dd229").First();
if (updateModel != null)
{
updateModel.Name = "Jerry";
var update_code = db.Updateable(updateModel).ExecuteCommand();//返回影响行数
}
// 5.删除数据
var delete_code = db.Deleteable<TestTable>().Where(it => it.Id == "8ffd64fc-8aea-4641-a57b-d957ad0dd229").ExecuteCommand();//返回影响行数
//6.自主封装的方法,有则添加无则插入(根据主键ID匹配)
var updateModel2 = new TestTable();
updateModel2.Id = "8ffd64fc-8aea-4641-a57b-d957ad0dd229";
updateModel2.Name = "SuSu";
int a = AddOrUpdate<TestTable>(db, updateModel2);//返回影响行数
}
}
【备注】AddOrUpdate是自己写的方法。