使用LINQ toSQL从存储过程返回新插入的行id

时间:2016-01-31 07:47:48

标签: c# sql-server linq stored-procedures

我有一个存储过程如下:

ALTER PROCEDURE [dbo].[Addworkshop]
    @title varchar(100),
    @time varchar(10),
    @date date,
    @mandatory int,
    @sid int
AS
BEGIN
    SET NOCOUNT ON;

    insert into Workshop(title, date, time, mandatory, sid)
    values(@title, @date, @time, @mandatory, @sid)

    declare @wid int
    set @wid = scope_identity()
    return @wid
END 

我从ASP.NET MVC5 C#中的action方法调用它:

public JsonResult addWorkshop(Workshop workshop)
{
        TLCWREntities context = new TLCWREntities();
        var wid = db.Addworkshop(workshop.title, workshop.time, workshop.date, workshop.mandatory, workshop.sid);
        return Json(wid);
}

使用JSON ajax调用此方法:

 $.ajax({

     type: 'POST',
     url: '@Url.Action("addWorkshop")', // we are calling json method

     dataType: 'json',

     data: $.toDictionary(wsData),


      success: function (wid) {
                        console.log("success add workshop wid: "+wid);

                    },
      error: function (ex) {
                        console.log("err add workshop");

                    }
                });

数据已成功插入到表中,当我在SQL Server Management Studio中执行存储过程时,它返回正确的新插入行ID。但是,当我使用JSON ajax和action方法调用存储过程时,它总是返回-1。

我正在使用Visual Studio 2013 MVC5 C#和SQL Server Studio 2008

3 个答案:

答案 0 :(得分:3)

在@ user2946329的帮助下以及Google上的一些搜索,我设法得到答案。 我改变了我的存储过程:

insert into Workshop(title, date, time, mandatory, sid)
values(@title, @date, @time, @mandatory, @sid)
declare @wid int
set @wid = SCOPE_IDENTITY()
select @wid AS wid

我使用select语句而不是return

返回了最后插入的行ID
  1. 在我的实体框架模型文件I updated model from database中,然后从模型浏览器导航到Function Imports,右键单击我的函数,然后单击编辑。我将返回值设置为Scalar enter image description here

  2. 我右键单击受该功能影响的模型并选择Stored Procedure Mapping enter image description here

  3. 我设置Result column binding并将返回ID与我的modelview的id绑定 enter image description here

    感谢大家帮忙

答案 1 :(得分:0)

在我创建存储过程以便在插入后返回ID的情况下,它会在我看来,我强烈推荐以下内容:

public JsonResult addWorkshop(Workshop workshop)
{
    TLCWREntities context = new TLCWREntities();
    db.Workshops.Add(workshop);
    db.SaveChanges(); //when this executes, `workshop` gets its `id` field populated
    return Json(workshop.sid);
}

答案 2 :(得分:0)

试试这个

int workShopId = 0;
using (TLCWREntities context = new TLCWREntities ())
{
    context.Workshop.InsertOnSubmit(workshop);
    context.SubmitChanges();
    workShopId = workshop.ID;//ID is column from you workshop table
}