Coding Duchess
Coding Duchess

Reputation: 6909

How to return identity value from Web API when posting to the database

I have two tables in my database that I am filling via Web API:

Orders
________
OrderID
OrderDate
OrderStatusID

and

OrderItems
___________
OrderID
ItemID
ItemNote
ItemSortOrder

and below is the method from my controller that I use to post Order to the database which works fine, I unit tested it previously.

[ResponseType(typeof(myClass.Order))]
[HttpPost]
public IHttpActionResult PostNewOrder(myClass.Order ord1)
{
      if (!ModelState.IsValid)
      {
          return BadRequest(ModelState);
      }
      using (MyContext ctx = new MyContext())
      {

          ctx.Orders.Add(ord1);
          ctx.SaveChanges();

          return CreatedAtRoute("DefaultApi", new { id = ord1.OrderID }, ord1);

      }
}

My question is - how can I return the OrderID of the newly inserted order from the database? OrderID field is an identity field in the database

Upvotes: 2

Views: 4277

Answers (3)

Igor
Igor

Reputation: 62228

ord1.OrderID will have the correct order id but you have to make sure that Entity Framework is mapped so that it knows the database will generate the value for the id. If you do that then the id is read back when you create your new order (or any entity that is added with an id column with that same mapping configuration applied).

You can map this on the id using either fluent mapping or an attribute. Here is the syntax for fluent:

modelBuilder.Entity<Order>()
    .Property(x => x.OrderID)
    .HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);

And for attributes

[DatabaseGenerated(DatabaseGenerationOption.Identity)] 
public int OrderID { get; set; }

If you are using the designer (.EDMX file) for mapping see the the image below as an example of how you can set the store generation pattern.

Properties

Image was copied from a previous SO answer. https://stackoverflow.com/a/6306817/1260204


  • Note - you should pick one or the other, not both.
  • I'm guessing on Entity Framework based on the name used in the context.

Upvotes: 1

Ben Hall
Ben Hall

Reputation: 1423

No need to add any new code.

As soon as you call ctx.SaveChanges(); the object ord1 will then have the new id in the property OrderID.

Upvotes: 4

matthijsb
matthijsb

Reputation: 909

You can do that by getting the Database values:

 var dbObject = ctx.Entry(ord1).GetDatabaseValues();
 return CreatedAtRoute("DefaultApi", new { id = dbObject["OrderID"] }, ord1);

Upvotes: 1

Related Questions