Reputation: 3143
I need to convert the following SQL insert statement to LINQ:
Insert into Car (Name)
Output inserted.CarId
Values ('Red Car')
This is my code so far :
using (MyContextEntities db = new MyContextEntities())
{
db.Entry(car).State = EntityState.Added;
db.SaveChanges();
}
How can I return the Id of the inserted item ?
Upvotes: 1
Views: 402
Reputation: 14899
After db.SaveChanges
you can access the id for example
car.Id
Can I return the 'id' field after a LINQ insert?
Upvotes: 2
Reputation: 18362
EF will set in your car instance:
using (MyContextEntities db = new MyContextEntities())
{
db.Entry(car).State = EntityState.Added;
db.SaveChanges();
return car.Id;
}
Upvotes: 2
Reputation: 7847
After SaveChanges, car instance already has generated Id
Also, why do you set state but not add an entity to context?
using (MyContextEntities db = new MyContextEntities())
{
db.Cars.Add(car);
db.SaveChanges();
}
return car.Id
Upvotes: 3