Search code examples
sqlrazorwebmatrix

Webmatrix - Creating two tables with the primary key from one


I currently have the following SQL statement which creates an entry in my database, and auto creates the primary key. This works fine:

if (IsPost){
var sql = "INSERT INTO Property_Info (PropertyName) VALUES (@0)";
db.Execute(sql, Request["propertyname"]);
}

What I also need to do on the same page, is insert a record into a different table, using the primary key created in the above statement. is this possible, or will i need to do this on a separate page?


Solution

  • Yep, you can get the database ID you created with db.GetLastInsertId() and use that as a parameter in your next query.

    http://msdn.microsoft.com/en-us/library/webmatrix.data.database.getlastinsertid(v=vs.111).aspx

    I've found that you are best off casting it to an int too, so immediately after your db.Execute() line, try this:

    int newId = (int)db.GetLastInsertId();