问题
I am using IDENTITY
columns in my SQL Server tables.
I have a unit test where I delete a data record with a certain id.
When I insert the testdata I get this exception:
Cannot insert explicit value for identity column in table 'MyTablename' when IDENTITY_INSERT is set to OFF
Then I do a quick test in my management studio:
SET IDENTITY_INSERT MyTablename ON
It says Command(s) completed successfully.
I rerun the unit test but still get the same error.
How do I go about that in general? I want that my unit testing database with all tables should allow me to insert a value manually for an identity column.
回答1:
SET IDENTITY_INSERT
is session-specific. You can't set it to true in SSMS and then go run a unit test in some other rig. The SET
command needs to be part of the unit test code.
Also, you can only set this setting to one table at a time, so it doesn't seem like your unit test will work very well unless you set each table as you need it.
来源:https://stackoverflow.com/questions/9404001/unit-testing-with-identity-columns