Search code examples
sql-serverentity-frameworklinqlinq-to-sqllinq-to-entities

adding PK into another column when inserting


I want to have the Primary Key inserted into another column using as below:-

Id  |  PaddedID |
----------------
6   |  0000006  |
7   |  0000007  |

Is there a way to achieve this in the db.SaveChanges() in one go? I know I can get the ID as below and update the PaddedID:-

int id = Result.Id;

Is there a way using LINQ to tell it take the PK pad it with some value and insert it in the PaddedID column?

Pointers appreciated....


Solution

  • You can use a persistant computed column for PaddedID using the FORMAT integrated function, like this:

    ALTER TABLE MyTable ADD PaddedID AS FORMAT(Id, '00000000') PERSISTED