看完这个例子你已经会使用SqlSugar做简单的数据库操作了,复制现有代码直接可以运行
代码
SqlSugarClient db = new SqlSugarClient(
new ConnectionConfig()
{
ConnectionString = "server=.;uid=sa;pwd=@jhl85661501;database=SqlSugar4XTest",
DbType = DbType.SqlServer,//设置数据库类型
IsAutoCloseConnection = true,//自动释放数据务,如果存在事务,在事务结束后释放
InitKeyType = InitKeyType.Attribute //从实体特性中读取主键自增列信息
});
//用来打印Sql方便你调式
db.Aop.OnLogExecuting = (sql, pars) =>
{
Console.WriteLine(sql + "\r\n" +
db.Utilities.SerializeObject(pars.ToDictionary(it => it.ParameterName, it => it.Value)));
Console.WriteLine();
};
/*查询*/
var list = db.Queryable<StudentModel>().ToList();//查询所有
var getById = db.Queryable<StudentModel>().InSingle(1);//根据主键查询
var getByWhere = db.Queryable<StudentModel>().Where(it=>it.Id==1).ToList();//根据条件查询
var total = 0;
var getPage = db.Queryable<StudentModel>().Where(it => it.Id == 1).ToPageList(1,2,ref total);//根据分页查询
//多表查询用法 http://www.donet5.com/Doc/8/1124
/*插入*/
var data = new Student() { Name = "jack" };
db.Insertable(data).ExecuteCommand();
//更多插入用法 http://www.donet5.com/Doc/8/1130
/*更新*/
var data2 = new Student() { Id =1, Name = "jack" };
db.Updateable(data2).ExecuteCommand();
//更多更新用法 http://www.donet5.com/Doc/8/1129
/*删除*/
db.Deleteable<StudentModel>(1).ExecuteCommand();
//更多删除用法 http://www.donet5.com/Doc/8/1128实体类
//如果实体类名称和表名不一致可以加上SugarTable特性指定表名
[SugarTable("Student")]
public class StudentModel
{
//指定主键和自增列,当然数据库中也要设置主键和自增列才会有效
[SugarColumn(IsPrimaryKey=true,IsIdentity =true)]
public int Id { get; set; }
public string Name { get; set; }
}
//当然也支持自定义特性, 这里就不细讲了根据实体创建表
你可以根据现有实体去手动创建一个表,当然也可以用 SqlSugar提供的根据实体创建表功能
db.CodeFirst.SetStringDefaultLength(200/*设置varchar默认长度为200*/).InitTables(typeof(StudentModel));//执行完数据库就有这个表了
总结:
SqlSugar是通过Queryable、Updateable、Deleteable和Insertable实现的增删查改
2016 © donet5.comApache Licence 2.0