I am confused by this behavior in LINQ. When I try to insert a value into an IDENTIY column using SQL I get an error. But when I try in LINQ I do not get an error and the insert value is ignored.
For example:
Table_1 has 2 columns. The first 'ID' is an IDENTITY(1,1) and increments on insert. Column 2 'TextColumn' is a varchar(50). If I run the following query in SQL:
insert into Table_1 (id,TextColumn) values (1,'test')
I get this error as expected:
Cannot insert explicit value for identity column in table 'Table_1' when IDENTITY_INSERT is set to OFF.
But when I run this code in C# no error is thrown:
var db = new TestDBDataContext();
var table1 = new Table_1();
table1.ID = 1; // SHouldn't this cause an error?
table1.TextColumn = "Test Text to insert";
db.Table_1s.InsertOnSubmit(table1);
db.SubmitChanges();
The int value '1' in this case is just ignored and the ID column auto increments normally. Here is the entry in the designer.cs file for the ID column
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_ID", AutoSync=AutoSync.OnInsert, DbType="Int NOT NULL IDENTITY", IsPrimaryKey=true, IsDbGenerated=true)]
I am confused why LINQ would not set these values to "Read Only" by default? If I toggle the Read Only property of the ID column I get the expected behavior. The Set method dissapears in the designer.cs for the ID object and an error appears in the code. Thank you!