0

I'm fairly new to this Web API stuff and I'm trying to set up simple http requests to a local database on my computer. I have a get request that looks like this:

[HttpGet]
[Route("")]
[Route("{ID:int}")]
public IQueryable<ListTable> Get(int id = -1)
{
    if(id == -1)
        return db.ListTables;
    else
        return db.ListTables.Where(lt => lt.ID == id);
}

This just returns all items in the database or one item relating to the specified ID. Now I'm trying to make a put request where I can add a new item to the database or edit item related to a certain ID. I was trying something like this:

[HttpPut]
[Route("{ID:int}")]
[Route("{ID:int}/{TITLE:string}")]
[Route("{ID:int}/{TITLE:string}/{DESCRIPTION:string}")]
public ListTable Put(int id = -1, string title = null, string descr = null)
{
    //if ID == -1 add a new item to the DB
    //else add title and description to the item with the specified ID
}

I am a little unsure of how to add a new item to the database and save the changes. I tried something like db.ListTables.Add(new ListTable()) and db.SaveChanges() but those didn't seem to actually save anything because when I called the Get() method again the new item wasn't there.

Wes Thompson
  • 462
  • 1
  • 5
  • 21

2 Answers2

1

You will need to new up an instance of the entity to add [ListTable] and then add it to your database context (assuming it's db based on your GET example. Once you add it to the context, then you .SaveChanges() - I'm assuming your ListTable entity has columns called Title and Description (change those lines to whatever you have them named):

ListTable listTableToAdd = new ListTable() 
{
    Title = title,
    Description = descr
}
db.ListTables.Add(listTableToAdd);
db.SaveChanges();
ethorn10
  • 1,889
  • 1
  • 18
  • 29
  • Hmm, this is basically what I did with a little different syntax. I must have something incorrect somewhere else then. I also have a warning that `db.SaveChanges()` is unreachable code... Not even sure how that's possible. – Wes Thompson Jul 31 '15 at 07:06
  • Actually ignore that first comment. I'm getting a "Validation failed for one or more entities" when I try `db.SaveChanges()`. – Wes Thompson Jul 31 '15 at 07:20
  • Ignore again! I solved it. One of my required fields was defaulting to null =/ Stupid mistakes. – Wes Thompson Jul 31 '15 at 10:15
0

You need to set the properties after new ListTable(). Something like new ListTable() { Title = title, ... }

Richard Schneider
  • 34,944
  • 9
  • 57
  • 73