2010-07-22 42 views
0

我们如何从一个存储过程LINQ到SQL - 如何返回一个值(插入,更新,删除)

这里返回值是我的SP的样子:

create proc dbo.spInsertGroup 
@ID uniqueidentifier 
@GroupName varchar(100), 
@IsActive bit 
AS 
BEGIN 



insert into tblGroup 
values(@ID, @GroupName, @IsActive) 

Select @@IDENTITY AS ID 

END 

基于关于返回值,我想向用户展示一些反馈,其中保存是成功或失败的。

public void AddInquiry(Inquiry inq) 
{ 
    using (var transaction = new TransactionScope()) 
    { 
     using (MyDataContext dc = conn.GetContext()) 
     { 
     var results = dc.spInquiry_Insert(......).ToList(); 

     transaction.Complete(); 

     var returnValue = (int)results.ReturnValue; 
     // note that ReturnValue is of type object and must be cast. 
     } 
    } 
} 

错误:

Error 39 'System.Collections.Generic.List' does not contain a definition for 'ReturnValue' and no extension method 'ReturnValue' accepting a first argument of type 'System.Collections.Generic.List' could be found (are you missing a using directive or an assembly reference?)

回答

1

尝试:

using (MyDataContext dc = conn.GetContext()) 
{ 
    var returnValue = (int)dc.spInsertGroup(.......).ReturnValue; 
} 

你得到这个错误,因为你所呼叫的.ToList()这样的VAR结果是类型列表<>没有ReturnValue属性。

如果你不能看到ReturnValue属性,也许你需要更新通过LINQ

产生
+0

错误我没有看到的返回值 – 2010-07-22 19:36:57

+1

什么spInsertGroup的返回类型方法? 编辑:应像ISingleResult Equiso 2010-07-22 19:43:37

0

对于像ID标量值,我相信你只是说 “RETURN @ID”

行集,我相信你选择它,类似你的例子,Linq2Sql将它作为IEnumerable<>导入。

更新:

既然你使用SELECT,L2S创建List<T>。由于select中的值是一个整数,因此只有一个元素List<int>。要检索它,它只是results[0]

或者你可以在存储过程更改为return @ID和使用:

var id = dc.spInquiry_Insert(......); 
+0

我刚才udpated我的问题与错误信息 – 2010-07-22 19:15:32

+0

我有一个RETURN @ID在我的SP,只更新,但仍然扔我,我上面贴的 – 2010-07-22 19:17:20

0

你不能,但一个INT从一个存储过程返回任何的方法,但是,你要发送一个GUID - 这是行不通的。您需要将存储过程改写为这样的:

CREATE PROCEDURE dbo.spInsertGroup 
    @GroupName varchar(100), 
    @IsActive bit, 
    @ID uniqueidentifier OUTPUT 
AS ....... 

然后它的好不够的,只是有SET @ID = NEWID()在你的存储过程 - 这工作得很好。

你的C#代码现在看起来是这样的:

using(YourDataContext ctx = new YourDataContext()) 
{ 
    Guid? newID = new Guid(); 
    bool? active = true; 

    int retVal = ctx.spInsertGroup2("test", active, ref newID); 
} 

newID将包含通话后的新ID。

+0

我没有得到ToList()可能是因为在我的SP我返回Return @ ID? – 2010-07-22 19:41:39

+0

我更新我的SP并返回..选择@@ IDENTITY AS ID 我仍然应该使用上面显示的内容吗? – 2010-07-22 20:23:35

+1

如果你有一个IDENTITY字段(你碰巧在你的文章中没有提到**),你可以检索,是的 - 但我建议你使用'SCOPE_IDENTITY()'而不是@@ IDENTITY - 请看这里: http://davidhayden.com/blog/dave/archive/2006/01/17/2736.aspx以及许多其他帖子(以及关于SO的问题)。 – 2010-07-22 21:05:58

相关问题