使用DAL对数据库表进行直接操作

129 129
XCode
sam
sam 2024-09-10 19:13:17

概述

使用newlife.xcode对数据库表进行直接操作

插入一条数据到数据库中

DAL dal = XCodeHelper.GetDal();

string code = Guid.NewGuid().ToString();
Dictionary<string, object> data = new Dictionary<string, object>();
data.Add("Code",Guid.NewGuid().ToString());
data.Add("RoleName","测试角色");
data.Add("DataDesc","描述11");
int rows = dal.Insert(data, "Adf_Role");

Console.WriteLine($"插入了几行:{rows}");

说明:使用Dictionary进行字段名与字段值插入到系统

更新一条数据

DAL dal = XCodeHelper.GetDal();

//Where条件是采用匿名类型,类似Dictionary ,可以考虑Dictionary来使用转换为匿名类型
var where = new {id=2};

string code = Guid.NewGuid().ToString();
Dictionary<string, object> data = new Dictionary<string, object>();
data.Add("RoleName", "调整后的测试角色");
data.Add("DataDesc", "更新后描述11");
int rows = dal.Update(data, where, "Adf_Role");

Console.WriteLine($"更新了几行:{rows}");

说明:Where条件是匿名数据类型,类似json,类似Dictionary

删除一条数据

DAL dal = XCodeHelper.GetDal();
var delWhere = new { idx = 3 };
dal.Delete("Adf_Role", delWhere);

使用事务对表进行操作

DAL dal = XCodeHelper.GetDal();

//开始事务
dal.BeginTransaction();

try
{
    // code 

    string code = Guid.NewGuid().ToString();
    Dictionary<string, object> data = new Dictionary<string, object>();
    data.Add("Code", Guid.NewGuid().ToString());
    data.Add("RoleName", "测试角色");
    data.Add("DataDesc", "描述11");
    int rows = dal.Insert(data, "Adf_Role");

    Console.WriteLine($"插入了几行:{rows}");

    var where = new { id = 2 };

    data = new Dictionary<string, object>();
    data.Add("RoleName", "调整后的测试角色");
    data.Add("DataDesc", "更新后描述11");
    rows = dal.Update(data, where, "Adf_Role");

    Console.WriteLine($"更新了几行:{rows}");

    var delWhere = new { idx = 3 };
    dal.Delete("Adf_Role", delWhere);

    dal.Commit();

}
catch (Exception ex)
{
    LogHelper.WriteLog(ex.Message);

    dal.Rollback();
}

说明,采用xcode开启后采用标准的事务模式,异常后进行回滚

回帖
  • 消灭零回复
作者信息
相关文章