0

I need to get id of newly created record form mssql. I read some information and still unclear. It says I can just do the following:

using (var context = new MyContext())
{
  context.MyEntities.AddObject(myNewObject);
  context.SaveChanges();

  int id = myNewObject.Id; // Yes it's here
}

Is it enough?

Igor Levashov
  • 658
  • 1
  • 13
  • 32

1 Answers1

1

Yes, Just you saved, you get the new value

be sure that you set the Identity attribute

[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int ID { get; set; }

Have a look for: C#, entity framework, auto increment

Community
  • 1
  • 1
M.Hassan
  • 10,282
  • 5
  • 65
  • 84