1、引入SqlSugar
2、新建SqlSugarConfig类
public class SqlSugarConfig { private static readonly string connectionString = "Data Source=localhost;Database=h2test;User Id=root;Password=root;charset=utf8;port=3306"; public static SqlSugarClient GetInstance() { var db = new SqlSugarClient(new ConnectionConfig() { ConnectionString = connectionString, DbType = DbType.MySql, IsAutoCloseConnection = true, InitKeyType = InitKeyType.Attribute }); return db; } }
3、新建实体Student类
public class Student { [SugarColumn(IsPrimaryKey = true, IsIdentity = true)] public int ID { get; set; } public string Name { get; set; } public string Pwd { get; set; } public int Role { get; set; } }
4、在程序启动的Program类中依赖注入Sqlsugar
internal static class Program { public static IContainer Container { get; set; } /// <summary> /// 应用程序的主入口点。 /// </summary> [STAThread] static void Main() { var builder = new ContainerBuilder(); // Register SqlSugarClient as a singleton builder.Register(c => SqlSugarConfig.GetInstance()).As<SqlSugarClient>().SingleInstance(); // Register forms builder.RegisterType<Form1>().AsSelf().InstancePerDependency(); Container = builder.Build(); Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(Container.Resolve<Form1>()); } }
5、在使用的窗体构造函数中引入
private readonly SqlSugarClient mysqldb; public Form1(SqlSugarClient db) { InitializeComponent(); this.mysqldb = db; }
6、开始使用
public BindingList<Student> Students; private void Form1_Load(object sender, EventArgs e) { //创建表 //创建表:根据实体类CodeFirstTable1 (所有数据库都支持) mysqldb.CodeFirst.InitTables(typeof(Student));//这样一个表就能成功创建了 Students =new BindingList<Student>( mysqldb.Queryable<Student>().ToList()); dataGridView1.DataSource = Students; }
标签:set,SqlSugarClient,get,db,static,Winform,public,sqlsugar,winform From: https://www.cnblogs.com/appform/p/17613267.html