How to get the ID of a newly added record in Entity Framework?
Hi! I'm new to C# and Entity Framework. I've encountered this problem: I'm adding a new entity to the database, but I need to immediately get its ID (primary key, auto-increment) to use it further in the code. For example, I create an order and immediately want to add order items that require the order ID.
Here's my code example:
```csharp
using (var context = new MyDbContext())
{
var order = new Order
{
CustomerName = "Ivan Ivanov",
OrderDate = DateTime.Now
};
context.Orders.Add(order);
context.SaveChanges();
// How do I get the order ID now?
// I tried order.Id, but it's 0!
Console.WriteLine(order.Id); // Outputs 0
}
```
I've tried different options, but the ID always returns 0 or null.
No answers yet.
Log in to leave an answer
Blogs