使用DataSet获取objectdatasource中最后插入项的id

时间:2011-01-23 23:10:07

标签: asp.net insert dataset objectdatasource

我已经做了很多关于此事的搜索,但我似乎无法找到任何人这样做过。我确定这是一个常见的问题,但我找不到合适的关键字来搜索解决方案,所以如果这是重复的话,我很抱歉。

我有一个数据集,我在其中使用了Generate Insert,Update和Delete语句以及Refresh the Data Table选项,以便在我使用ObjectDatasource时可以检索最后插入的ID。

然而,当我处理ObjectDataSource-Inserted方法时,我得到1作为返回值,我假设是受影响的行。我不希望这样,我想要ID,以便我可以在我的代码中使用它。

我查看了insert方法生成的代码,插入后它正在执行SELECT,但它返回的是整行而不是ID,那么如何才能在此行中获取值?

1 个答案:

答案 0 :(得分:0)

我过去做过的事情是使用静态方法进行CRUD操作。

<ObjectDataSource runat="server" ID="_odsThingy"
        TypeName="Northwind.ThingyFactory" SelectMethod="Select" InsertMethod="Insert">
    <SelectParameters>
        <SessionParameter Name="id" SessionField="thingyId" />
    </SelectParameters>
</ObjectDataSource>

和C#代码:

class ThingyFactory {
    public static DataSet Select(int id, /* other criteria for selecting? */) {
        // ...
    }

    public static int Insert(/* values required for insert */) {
        // do insert & return the ID
    }
}

我还没有尝试编译这段代码,所以如果我犯了一些错误,我会道歉。由于获得了控制权,这种特殊的模式让我摆脱了一些困境。有关其工作原理的详细信息,请阅读this article

相关问题