public class Repository三、建立对应的实体类,这里我们建一个名为AdminInfo的实体类。: SimpleClient where T : class, new() { public Repository(ISqlSugarClient context = null) : base(context)//注意这里要有默认值等于null { if (context == null) { base.Context = new SqlSugarClient(new ConnectionConfig() { DbType = SqlSugar.DbType.PostgreSQL, InitKeyType = InitKeyType.Attribute, IsAutoCloseConnection = true, MoreSettings = new ConnMoreSettings() { PgSqlIsAutoToLower = false //数据库存在大写字段的 ,需要把这个设为false ,并且实体和字段名称要一样 }, ConnectionString = "PORT=5630;DATABASE=tshoteldb;HOST=localhost;PASSWORD=postgres;USER ID=postgres" }); base.Context.Aop.OnLogExecuting = (s, p) => { Console.WriteLine(s); }; } }
注意:[SqlSugar.SugarTable(“表名”)]建议都强制加上,以及数据库字段的[SqlSugar.SugarColumn(ColumnName = “字段名”)]也强制加上,否则容易报“关系‘xxxx’不存在…”等类似的错。
[SqlSugar.SugarTable("admininfo")]
public class AdminInfo
{
[SqlSugar.SugarColumn(ColumnName = "AdminAccount")]
public string AdminAccount { get; set; }
[SqlSugar.SugarColumn(ColumnName = "AdminPassword")]
public string AdminPassword { get; set; }
[SqlSugar.SugarColumn(ColumnName = "AdminType")]
public string AdminType { get; set; }
[SqlSugar.SugarColumn(ColumnName = "AdminName")]
public string AdminName { get; set; }
[SqlSugar.SugarColumn(ColumnName = "IsAdmin")]
public int IsAdmin { get; set; }
[SqlSugar.SugarColumn(ColumnName = "DeleteMk")]
public int DeleteMk { get; set; }
}
四、接下来就可以开始写业务逻辑了,我们这里建一个名为AdminService并且继承Repository,<>里对应的是要操作的实体类名称。
public class AdminService : Repository五、最后进行调用。{ public List GetLists() { var list = base.GetList(a => a.DeleteMk != 1); return list; } }
static void Main(string[] args)
{
Console.WriteLine(string.Join("n", new AdminService().GetLists().Select(a => a.AdminAccount)));
Console.ReadKey();
}
六、运行结果:
七、总结:
其实SQLSugar已经做了大部分与数据库打交道的工作了,我们只是稍微改下配置即可,但是SQLSugar版本要与Npgsql版本要兼容匹配,否则会出现各种各样的报错,之前就因为这样烦恼了楼主两天时间,唉,归咎只是自己太菜。最后,如果大家知道其他SQLSugar版本和Npgsql版本可以兼容的话可以写在文章下方,汇总成一个表格方便大家更愉快地使用SQLSugar+PostgreSQL吧!
成一个表格方便大家更愉快地使用SQLSugar+PostgreSQL吧!



