在c#中使用linq执行存储过程

cha*_*rhy 4 c# sql linq sql-server-2008 linq-to-sql

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

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
Run Code Online (Sandbox Code Playgroud)

上面的过程在sql server中运行正常.但是当我在C#中使用linq运行此语句时

        mytestDataContext obj = new mytestDataContext();
        var test=obj.ExecuteCommand("dbo.getlog");
        foreach( var abc in test)
        {}
Run Code Online (Sandbox Code Playgroud)

我收到这个错误

错误1 foreach语句不能对'int'类型的变量进行操作,因为'int'不包含'GetEnumerator'的公共定义

Sim*_*ead 7

ExecuteCommand返回int..不是你的结果.

请在此处查看MSDN:http://msdn.microsoft.com/en-us/library/system.data.linq.datacontext.executecommand.aspx

public int ExecuteCommand(
    string command,
    params Object[] parameters
)
Run Code Online (Sandbox Code Playgroud)

我想你是在追求ExecuteQuery.


Son*_*nül 5

ExecuteCommand方法返回Int32,并且您不能使用foreach简单整数来使用神奇循环。

Return Value
Type: System.Int32
The number of rows modified by the executed command.
Run Code Online (Sandbox Code Playgroud)

我对类不太熟悉DataContext,但您可以使用DataContext.ExecuteQuerywhich returns IEnumerable<TResult>,并且可以使用foreachloop。

Return Value
Type: System.Collections.Generic.IEnumerable<TResult>
Run Code Online (Sandbox Code Playgroud)

查询返回的对象的集合。