I'm trying to create an application using Angular and Web API for some simple CRUD operations.
I succeeded in connecting the Web API and Angular to my database, but whenever I make a POST
request (even if I don't have anything in my database), my Id starts from the "remembered" last number of TimeId
and I would like for it to start from 1 if my database is empty.
Can anyone tell me why is this happening and how to fix this?
I made my POST
request and it looks like this in database:
Now if I delete this using TimeId
(using Swagger) my database will be empty.
But if I try to make another POST
request, my TimeId
will not start from 1 but from 35:
My POST
methods in the Web API are:
[HttpPost]
public async Task<ActionResult<Time>> PostTime(Time time)
{
_context.Times.Add(time);
await _context.SaveChangesAsync();
return CreatedAtAction("GetTime", new { id = time.TimeId }, time);
}
and GetTime
method is:
[HttpGet("{id}")]
public async Task<ActionResult<Time>> GetTime(int id)
{
var time = await _context.Times.FindAsync(id);
if (time == null)
{
return NotFound();
}
return time;
}
When I do the POST
request from Angular side, the same thing happens, but I suppose this is because Angular is using POST
method from the Web API.
CodePudding user response:
It has nothing to do with Delete operation.
If you allow database to automatic increment value on insert then this is the behavior you get.
Also you have to understand different between Delete, Truncate and RESEED.
So if you really want to reset it to 1 again then you have to execute following in your SQL Server DB ( DB in which table contains record)
DBCC CHECKIDENT ('your table name', RESEED, 1)
GO
Note : You have not specified DB so my solution will work for SQL Server.