这里用的是Dapper,以前用EF的时候好像有用到过db.savechanges(). 但是项目中没有这个,所以用以下的方法去获取id
背景:涉及到多表入库,需要获取主表的Id,所以用到了这个(timeFields 可以忽略)
/// <summary> /// 单个添加 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="t"></param> /// <param name="timeFields"></param> public int AddBackId<T>(T t, List<string> timeFields = null) { var sql = GetSql(InsertSql, timeFields); if (!sql.EndsWith(";")) { sql += ";"; } if (!sql.EndsWith("SELECT LAST_INSERT_ID();")) { sql += "SELECT LAST_INSERT_ID();"; } return DB.Query<int>(sql, t).FirstOrDefault(); }
private string GetSql(string oSql, IEnumerable<string> timeFields = null) { var fields = new List<string>(); fields.AddRange(TimeFields); if (timeFields != null && timeFields.Any()) { fields.AddRange(timeFields.Where(x => !TimeFields.Contains(x))); } var sql = oSql; if (fields.Any()) { foreach (var field in fields) { sql = sql.Replace($"@{field}", $"IF(@{field} = '0001-01-01 00:00:00', NULL, @{field})"); } } return sql; }
标签:自增,fields,timeFields,主键,field,sql,var,Id From: https://www.cnblogs.com/cyqdeshenluo/p/18281057