I have a table that has an Identity column and another column needs to have its value based on the computed identity column.
My EF code looks like this:
var context = new DBEntities();
var newTableRow = new TableRow();
newTableRow.Column1 = newTableRow.ComputedColumn;
context.TableRows.Add(newTableRow);
context.SaveChanges();
If ComputedColumn is an IDENTITY and Column1 is a nullable varchar(50) I would expect the value of Column1 to be the same as the ComputedColumn but it is null.
I have even tried this:
var context = new DBEntities();
var newTableRow = new TableRow();
context.TableRows.Add(newTableRow);
context.SaveChanges();
newTableRow.Column1 = newTableRow.ComputedColumn;
context.SaveChanges();
AND
var context = new DBEntities();
var newTableRow = new TableRow();
context.TableRows.Add(newTableRow);
context.SaveChanges();
var getTableRow = context.TableRows.Single(r => r.ComputedColumn == newTableRow.ComputedColumn);
getTableRow.Column1 = newTableRow.ComputedColumn.ToString();
context.SaveChanges();
Keep in mind that this is part of a larger transaction. What I don’t want to do is complete the transaction then in a separate transaction do another update. I would like to keep everything in one transaction. This had been working in an insert proc before.
Thanks,
Brett
Your second an third example should work if
ComputedColumnhasDatabaseGeneratedOption.Identity. But they have separate transactions, which you don’t want.Your first example can’t work. When a column has
DatabaseGeneratedOption.Identity, EF reads the identity value back when executingSaveChanges. It is not aware of any special instruction you might have tried to convey withAs for EF, it’s just an assignment with an empty value.
Maybe the best alternative is to add a computed column to your database table. You will kill two birds with one stone: