在 Winform 中使用 SqlSugar 首先需要安裝 SqlSugar 包,可以通過 NuGet 包管理器搜索并安裝 SqlSugar。
using SqlSugar;
public class DatabaseContext
{
private SqlSugarClient db;
public DatabaseContext()
{
db = new SqlSugarClient(new ConnectionConfig()
{
ConnectionString = "YourConnectionString",
DbType = DbType.SqlServer,
IsAutoCloseConnection = true
});
}
public List<T> GetAll<T>() where T : class, new()
{
return db.Queryable<T>().ToList();
}
public T GetById<T>(object id) where T : class, new()
{
return db.Queryable<T>().InSingle(id);
}
public void Insert<T>(T entity) where T : class, new()
{
db.Insertable(entity).ExecuteCommand();
}
public void Update<T>(T entity) where T : class, new()
{
db.Updateable(entity).ExecuteCommand();
}
public void Delete<T>(T entity) where T : class, new()
{
db.Deleteable(entity).ExecuteCommand();
}
}
在 Winform 窗體中使用 DatabaseContext 類來進行數據庫操作:
private void btnGetAll_Click(object sender, EventArgs e)
{
DatabaseContext dbContext = new DatabaseContext();
var data = dbContext.GetAll<YourEntity>();
dataGridView.DataSource = data;
}
private void btnInsert_Click(object sender, EventArgs e)
{
DatabaseContext dbContext = new DatabaseContext();
YourEntity entity = new YourEntity { Name = "Test" };
dbContext.Insert(entity);
}
private void btnUpdate_Click(object sender, EventArgs e)
{
DatabaseContext dbContext = new DatabaseContext();
YourEntity entity = dbContext.GetById<YourEntity>(1);
entity.Name = "Updated";
dbContext.Update(entity);
}
private void btnDelete_Click(object sender, EventArgs e)
{
DatabaseContext dbContext = new DatabaseContext();
YourEntity entity = dbContext.GetById<YourEntity>(1);
dbContext.Delete(entity);
}
在上面的代碼中,需要將 “YourConnectionString” 替換為實際的數據庫連接字符串,以及將 “YourEntity” 替換為實際的實體類名稱。通過 DatabaseContext 類的方法實現數據庫的增刪改查操作,并在 Winform 窗體的按鈕點擊事件中調用這些方法來操作數據庫。