Abdulaziz Yahya
Abdulaziz Yahya

Reputation: 327

Delete method issue - Asp.net Web API

I have a POST Method which is working fine it takes a list of object and add it to the database with Entity Framework AddRange

I tried to apply the same logic with the DELETE method (takes list of objects and delete it from the database with RemoveRange) it does return 200 OK but does not delete from the database

POST

[HttpPost]
        public HttpResponseMessage Post(List<Provider_status> rows)
        {
            try
            {
                using (DbModel dbModel = new DbModel())
                {
                    dbModel.Provider_status.AddRange(rows);
                    dbModel.SaveChanges();
                }
            }
            catch { }
            return new HttpResponseMessage()
            {
                Content = new StringContent("Records Added")
            };
        }

DELETE method

[HttpDelete]
        public HttpResponseMessage Delete(List<Provider_status> rows)
        {
            try
            {
                using (DbModel dbModel = new DbModel())
                {
                    dbModel.Provider_status.RemoveRange(rows);
                    dbModel.SaveChanges();
                }
            }
            catch { }
            return new HttpResponseMessage()
            {
                Content = new StringContent("Records Deleted")
            };
        }

Upvotes: 1

Views: 416

Answers (2)

Serge
Serge

Reputation: 43959

Try this

foreach ( var row in rows)
{
var exRow= dbModel.Provider_status.FirstOrDefault(i=> i.Id==row.Id);
if( exRow!=null) dbModel.Provider_status.Remove(exRow);
}
dbModel.SaveChanges();

and IMHO remove [HttpDelete] from the action

Upvotes: 1

Tom W
Tom W

Reputation: 5422

A possible cause is that

dbModel.Provider_status.RemoveRange(rows);

Is comparing rows to Provider_status using reference equality and considering that since none match, none should be removed.

Upvotes: 0

Related Questions