如何编写此存储过程

时间:2012-11-06 02:54:32

标签: c# stored-procedures entity-framework-4

我有一张桌子Student。此表有一列ID,它是自动递增的。我想编写一个存储过程来添加一个新学生并返回ID。我是新手。

这是我的代码。请检查它是否错误并为我修复并告诉我如何在C#中使用它进行编码。我使用了Entity Framework 4.

@Name NVARCHAR(50),
@Birthday DATETIME, 
@ID bigint OUTPUT 
AS 
BEGIN
    SET XACT_ABORT ON 

    BEGIN 
       INSERT INTO [Student](Name, Birthday) VALUES (@Name, @Birthday);  
       SELECT @ID = SCOPE_IDENTITY()
    END
END

3 个答案:

答案 0 :(得分:3)

当您使用C#时,最好能SP代替EF4

使用Entity Framework,这一切都是自动完成的。

using (MyEntities context = new MyEntities())
{
    var student =  new Student()
    {
      Name = "some value",
      Birthday = "some Birthday"
    };

    context.Students.AddObject(student);

    context.SaveChanges();

    int ID = student.ID; // You will get here the Auto-Incremented table ID value.
}

保存在实体框架中将自动更新“自动增量”ID列。您只需在调用.SaveChanges();

之后将其读出来

编辑:

如果您在获取“自动增加”ID值时遇到任何问题,请阅读此post

答案 1 :(得分:0)

@Name NVARCHAR(50),
@Birthday DATETIME, 
@ID bigint OUTPUT
AS
BEGIN
SET XACT_ABORT ON   
BEGIN 

    INSERT INTO [Student](Name,Birthday)
    VALUES(@Name,@Birthday);

    SELECT @ID = SCOPE_IDENTITY()
END

我刚在字段之间添加了逗号

答案 2 :(得分:-1)

http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.aspx

这应该为您提供构建调用存储过程的C#应用​​程序所需的所有信息。

相关问题