We have recently added a new "level" to our database - added a key "Company_ID" to be above/before the existing ID Identity field in the tables throughout the database.
For example, if a Table had ID then fields, it now has Company_ID, then ID, then the fields. The idea is that this allows ID to auto-increment for each different Company_ID value that is provided to the functionality (Company_ID 1 can have ID 1, 2, 3 etc ; Company_ID 2 can have ID 1, 2, 3, etc).
The auto-increment field remains as ID. An example table is :
[dbo].[Project](
[Company_ID] [int] NOT NULL,
[ID] [int] IDENTITY(1,1) NOT NULL,
[DescShort] [varchar](100) NULL,
[TypeLookUp_ID] [int] NULL,
[StatusLookUp_ID] [int] NULL,
[IsActive] [bit] NOT NULL,
CONSTRAINT [PK_Project] PRIMARY KEY CLUSTERED
(
[Company_ID] ASC,
[ID] ASC
)
Before the Company_ID was introduced, to perform a CREATE, we simply populated the DescShort, TypeLookUp_ID, StatusLookUp_ID and IsActive fields, and left ID to be whatever it was by default, possibly 0.
The record was saved successfully, and ID was auto-populated by the database, and then used to perform a SHOW via a View, and so on.
Now, however, we want to set Company_ID to a specified value, leave ID, and populate the fields as before.
_db.Project.Add(newProject);
_db.SaveChanges();
Yes, we want to specify the Company_ID value. We want the ID to be auto-populated, as per before. We are getting the error message :
Cannot insert explicit value for identity column in table "Project" when IDENTITY_INSERT is set to OFF
Is this caused by specifying the Company_ID, or by the ID field? Do you know how we can rectify this issue?
IDENTITYspecification is ever increasing and you cannot insert a value to it withoutIDENTITY_INSERTswitched on for that field. You won't getCompany_ID1 havingID1, 2, 3 andCompany_ID2 havingID1,2,3 etc. You'll getCompany_ID1 havingID1,2,3 andCompany_ID2 having 4ID4,5,6. This might not be an issue for you, but just to make you aware,IDwon't care whatCompany_IDhas in it and will not change it's behaviour. - Steve PettiferCompany_ID1 havingID1, 2, 3 andCompany_ID2 havingID4, 5, 6. Thank you for bringing this to our attention - the initial investigator on this has been sacked! ;) If our client Companies were to merge (which has occurred to us in the past), having "duplicated"IDvalues in the database would not allow for easy merging of data. This way, we "simply" update theCompany_IDvalues for the data and away we go. Thank you again. - and_E