Incorrect ID is returned after insert using TableAdapter

馋奶兔 提交于 2019-12-08 19:37:50

问题


When I perform an insert with TableAdapter:

int pid = this.purchaseTableAdapter.Insert(supplierid, datetime, "", 
    totalprice, amountpaid);

It returns the incorrect id 1 while it should return 15.

How to get the correct ID?


回答1:


set the execute mode property to Scalar, then you get the ID, otherwise the rows-affected. You set the property properties window of the query not in the Query wizard.

(fig 28)




回答2:


The table adapter returns the number of rows affected not the id.




回答3:


I'm assuming that you have a pid column with an autogenerated value.

The reply to this post has the answer.

select @@pid 

From the same open connection should do it.




回答4:


1) The stored procedure:

The body of your stored procedure must be similar to this:

INSERT INTO MyTable (C1, C2, C3) VALUES (@c1, @c2, @c3);

SELECT SCOPE_IDENTITY();

The important part here is to use SELECT SCOPE_IDENTITY() and not RETURN SCOPE_IDENTITY(). Edit: using RETURN will work if you are calling a function instead of a stored procedure.

2) The table adapter:

Right click on your table adapter and select Add Query from the context menu. The TableAdapter Query Configuration Wizard pops-up:

  • Choose a Command Type: select "Use existing stored procedure".

  • Choose the shape of data returned by the SP: select "A single value".

  • Enter an appropriate name for the method, e.g. InsertXYZ

3) Your code:

Now, when you call the method InsertXYZ on your table adapter, it will return an object which you can cast to Int32. That value is the ID of the new record!




回答5:


How about this post ASP.NET tableadapter insert not returning the correct identity value

I really do not know c# but the function may be returning the number of rows affected, or a boolean 1 for true or 0 for false ?



来源:https://stackoverflow.com/questions/4776655/incorrect-id-is-returned-after-insert-using-tableadapter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!