2013-06-25 33 views
3

我在sql server 2008中创建了一个存储过程,它使我对表进行了更改。我正在使用Linq to SQL在C#中使用此表。 我的存储过程是在c#中使用linq执行存储过程#

CREATE PROCEDURE dbo.getlog 
    -- Add the parameters for the stored procedure here 
@p1 int = 0, 
@p2 int = 0 
AS 
BEGIN 
-- SET NOCOUNT ON added to prevent extra result sets from 
-- interfering with SELECT statements. 
SET NOCOUNT ON; 

    -- Insert statements for procedure here 
DECLARE @from_lsn binary(10), @to_lsn binary(10) 
SET @from_lsn = 
sys.fn_cdc_get_min_lsn('dbo_User_Info') 
SET @to_lsn = sys.fn_cdc_get_max_lsn() 
SELECT ID_number, Name, Age FROM cdc.fn_cdc_get_all_changes_dbo_User_Info 
(@from_lsn, @to_lsn, N'all'); 
END 
GO 

上述过程在sql server中运行良好。然而,当我在C#中运行使用LINQ这一说法

 mytestDataContext obj = new mytestDataContext(); 
     var test=obj.ExecuteCommand("dbo.getlog"); 
     foreach(var abc in test) 
     {} 

我得到这个错误

错误1 foreach语句不能对类型“诠释” 的变量操作,因为“诠释”不包含公共定义 '的GetEnumerator'

回答

3

ExecuteCommand方法返回Int32,你不能使用魔法foreach循环使用一个简单的整数。

Return Value 
Type: System.Int32 
The number of rows modified by the executed command. 

我不是DataContext类太多熟悉的,但你可以使用DataContext.ExecuteQuery返回IEnumerable<TResult>,你可以使用foreach循环吧。

Return Value 
Type: System.Collections.Generic.IEnumerable<TResult> 

由查询返回的对象的集合。

1

我不知道为什么你使用的foreach语句,但法“ExecuteCommand的回报int值,和foreach循环需要对象实现IEnumerable

0

我可以假设太多,但如果您使用的是最新版本的Visual Studio做的C#,而是直接指定T-SQL调用运行存储过程作为文字文本字符串,你可以拖动并将存储过程放到LINQ to SQL建模窗口中。这将把它添加到LINQ to SQL数据上下文中。

int param1 = 1; 
int param2 = 2; 

mytestDataContext obj = new mytestDataContext(); 
var test=obj.getlog(param1, param2); 
foreach(var abc in test) 
{ 
    /* code inside loop */ 
} 

同样的技术可以用于调用用户定义的函数。

这样做会减少打字和提供intellisense以帮助调用存储过程和SQL函数。

0

你可以使用这个库: https://github.com/mrmmins/C-StoreProcedureModelBinding

返回值作为一个表,你只需要创建一个简单的类名和值类型,如:

var productos = DataReaderT.ReadStoredProceadures<MyCustomModel>(myDbEntityInstance, "dbo.MySPName", _generic); 

和MyCumtomModel类是这样的:

public int id {get; set;} 
public int salary {get; set;} 
public string name {get; set;} 
public string school {get; set;} 

和通用这样的:

List<Generic> _generic = = new List<Generic> 
          { 
           new Generic 
            { 
             Key = "@phase", Type = SqlDbType.Int, Value = "207" 
            } 
          } 
         }; 

而现在,你products有选项,如:products.First()products.Count()foreach