public static long GetNewId(this DbContext db, string name)
{
var connectionString = db.Database.GetDbConnection().ConnectionString;
return GetNewId(connectionString, name);
}
public static long GetNewId(string connectionString, string name)
{
var options = new DbContextOptionsBuilder<CoreDbContext>()
.UseSqlServer(connectionString)
.Options;
using var db = new CoreDbContext(options);
// 最多尝试1千次
for (int i = 0; i < 1000; i++)
{
var model = db.Set<CRM_NewId>()
.Where(m => m.Name == name)
.FirstOrDefault();
if (model == null)
{
throw new Exception("指定的NewId记录未配置");
}
try
{
model.NewId++;
db.SaveChanges();
return model.NewId;
}
catch (Exception ex)
{
}
}
throw new Exception("未能获取到最新的NewId");
}