get identity when adding via entity framework

63 Views Asked by At

I'm using entity framework to insert a new record into my templates database. I would like to know what the identity of the inserted record is after the insert is done.

my code for inserting the record...

WEBSITE_ORDER_LINE_TEMPLATES newTemplate = new WEBSITE_ORDER_LINE_TEMPLATES();
newTemplate.customerNo = Customer.CustomerNo;
newTemplate.templateName = txtSaveTemplate.Text.Trim();
dpot.WEBSITE_ORDER_LINE_TEMPLATES.Add(newTemplate);

i want to know what the templateId is... in sql, this field is set as primary key and IsIdentity=Yes.

is there a quick way to get this value without searching the database where customer and templatename match? I need to know the ID because after this part, i want to enter template line information and there's a foreign key on that table on the templateId in this table.

1

There are 1 best solutions below

0
On

Call the SaveChanges() method. EF updates the newTemplate.templateId with SELECT SCOPE_IDENTITY() after the INSERT.