How to get the id for insertion in to a DB in WebApi using Entity Framework?

Just experimenting with Azure & WebApi.

Have this model:

public class ModelClass
{
    public int Id {get;set;}
    public int Model {get;set;}
}

There is this method, which creates a new resource.

[ResponseType(typeof(ModelClass))]
public IHttpActionResult PostModelClass(ModelClass obj)
{
    if (!ModelState.IsValid)
    {
        return BadRequest(ModelState);
    }

    dbContext.ModelClass.Add(bankModel);
    dbContext.SaveChanges();

    return CreatedAtRoute("DefaultApi", new { id = ModelClass.Id }, obj);
}

But, this forces me to supply a parameter called id which has to be unique.

How can I delegate this responsibility to the DB to create a new id ?

I can, for the moment, think of getting the last updated id from the database & then supply it to the obj.

But is there any cleaner or any inbuilt way?

Upvotes: 0

Views: 55

Answers (1)

Lukas Kabrt
Lukas Kabrt

Reputation: 5489

In standard circumstances (by convention ID is the primary key), ID property gets populated automatically by EF when you save changes to the database.

Upvotes: 1

Related Questions