user3340627
user3340627

Reputation: 3143

Linq insert statement with return value

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

Answers (3)

Oluwafemi
Oluwafemi

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

Thiago Custodio
Thiago Custodio

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

Artiom
Artiom

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

Related Questions