Search code examples
asp.netsqldatabaselambdaautonumber

Auto generated ID from DB in ASP.NET


I have a primary key for my table employee. I named it "IDS". The IDS data is like : K-00001, K-00002, etc. what I want to ask is, how to made this IDS auto generate in ASP.NET, not using trigger or function in SQL?

I have done my code like this:

            DBRabbit _db = new DBRabbit();
            Employee k = new Employee();
            var row = (from r in _db.Employees
                       orderby r.IDS descending
                       select r).FirstOrDefault();
            var n = row.IDS.PadLeft(5, '0');    
            IDSText.Text = n.ToString();

And I'm stuck while think how to adding the 'n' to + 1.. because when I write like this:

var n = row.IDS.PadLeft(5, '0')+1; 

(last record is K-00010)
the result is K-000101 how to make it K-00011 without changing DB or using SQL server script/queries?


Solution

  • You better make your IDS column auto incremented as James said. Also if you need to have another column for K-00010, K-00011,... I would suggest you to use a computed column with the following formula

    'K-' + cast( right([IDS]+(100000),(5)) as varchar(5))
    

    EDIT: Formula corrected.