生成主键,拒绝GUID
直接上代码
using System; using System.Collections.Generic; using System.Text; namespace Library { public class ParmaryKeyHelper { /// <summary> /// 获取主键 /// </summary> /// <returns></returns> public static string GetPrimaryKey() { DateTime detNow = DateTime.Now; try { return string.Format("086028000{0}{1}", detNow.ToString("yyyyMMddHHmmss"), PrimaryKey.GetParamSequence()); } catch (Exception ex) { throw new Exception("获取主键时发生错误:" + ex.Message); } } } class PrimaryKey { private static object objParam = new object(); private static int ParamNo = 0; /// <summary> /// 获得系统参数序号 /// </summary> /// <returns>序号值</returns> public static string GetParamSequence() { lock (objParam) { ParamNo++; if (ParamNo == 100000) ParamNo = 1; return ParamNo.ToString("00000"); } } } }
调用
ParmaryKeyHelper.GetPrimaryKey();
优点:可以按照主键排序,可以追溯创建时间