How to Create my own custom ID - SqlServer

Posts   
 
    
Reginald
User
Posts: 24
Joined: 20-Jan-2006
# Posted on: 11-Nov-2009 13:01:55   

Hello,

I'm wanting to create my own custom ID generated through code. The DB field is a decimal value and the ID I'll generate will be something like 9230012.782001. Nothing too tough there but just wondering how to make this happen?

The reason I'm doing this is because I'm using MS Sync Framework and it requires that you insure that all ID's are unique across all synchronized nodes. The easy way would be to use a GUID as the PK field but I'd like to use an ID that has meaning. My code to generate an ID would be like the code below...



        public static decimal GetNewId()
        {
            DateTime dt = DateTime.Now;
            string id = "";

            id += Convert.ToInt32(dt.ToString("yy")).ToString(); // add year and without leading zero
            id += dt.AddDays(1d).Subtract(DateTime.Parse("1/1/" + DateTime.Now.Year.ToString())).Days.ToString("000");
            id += dt.ToString("HHmmss"); // Add hour minute second
            id += ".";
            id += Convert.ToInt32(dt.ToString("fff")).ToString("000"); // Add fraction aka millisecond
            id += NodeId.ToString(); // add the node id

            return Convert.ToDecimal(id);
        }

Is there a way to do this and is there a way to have every "Save" command automatically use this function?

Walaa avatar
Walaa
Support Team
Posts: 14993
Joined: 21-Aug-2005
# Posted on: 11-Nov-2009 15:27:18   

You can use the Validation framework, and in ValidateEntityBeforeSave you can inject the ID value.