Reputation: 6909
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
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.
Image was copied from a previous SO answer. https://stackoverflow.com/a/6306817/1260204
Upvotes: 1
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
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