-1

I have a form view which people use to update a record in the database. However initially the record will not exist, and all fields will show their default values. The first time the submit button is clicked, the record should be created in the database. Subsequent submits should update the existing record. The record is identified by it's primary key, which is passed to be page via Request.QueryString.

Does ASP.net provide a simple way of doing this, or do I need to roll my own implementation of the insert/update logic?

4

2 回答 2

2

Read the value and do a GET request to your data source/Repositary. Check whether there is already an Entity / Record exist for this key. If yes call your Update method, else Insert.

Something like this

 //check the queystring param value is valid numeric expression 
//before trying to convert

 int itemId=Convert.ToInt32(Request.QueryString["itemId"]);

 var item=repo.GetItemById(itemId);
 if(item==null)
 {
   repo.InsertItem(item);
 }
 else
 {
    repo.UpdateItem();
 }

Assuming repo is an object of your Repositary implementation where you have the Insert and UupdateItem methods present which will do the updation/insertion of data to your persistant storage.

于 2012-07-02T16:14:33.983 回答
2
UPDATE dbo.table SET col = @col WHERE id = @id;

IF @@ROWCOUNT = 0
BEGIN
  INSERT dbo.table(id, col) SELECT @id, @col;
END

In 2008+ you can also use MERGE but I find the syntax quite daunting (and it doesn't isolate you from potential collisions as well as you might think it does).

于 2012-07-02T16:25:54.893 回答