2017-10-12 79 views
1

以下存儲過程顯示三個字符串和一個表格行結果作爲輸出。 有什麼辦法可以使用實體框架在mvc視圖輸出面板上顯示所有結果?使用實體框架從存儲過程獲取多個字符串輸出

我可以在下面的代碼中看到第一個字符串結果。但是無論如何要得到另外兩個選擇字符串輸出和 表格結果。

private CustomerEntities db = new CustomerEntities(); 
     public ActionResult Index() 
     { 
      var results = db.usp_CustomerData("124544", 1500); 
      var abc = results.ToList(); 
      return View(); 
     } 

ALTER PROCEDURE [dbo].[usp_CustomerData] 
@CustomerID varchar(6), 
@MinsBack int 
AS 
BEGIN 

    DECLARE @Count int 
    SET @Count = (SELECT Count(*) 
        FROM Customer WITH (NOLOCK) 
        WHERE CustomerID = @CustomerID AND      
          DATEDIFF(mi, ReceivedAt, GETUTCDATE()) < @MinsBack) 
    IF (@Count = 1) 
     SELECT 'Ok: 1 message in Customer table' 
    ELSE 
     SELECT 'ERROR: Expected 1 message in Customer table, but found ' + CONVERT(varchar(3), @Count) + ' messages.' 


    SET @Count = (SELECT Count(*) 
        FROM CustomerDetails WITH (NOLOCK) 
        WHERE CustomerID = @CustomerID AND 
          DATEDIFF(mi, LastUpdatedAt, GETDATE()) < @MinsBack) 
    IF (@Count = 1) 
     SELECT 'Ok: 1 record in CustomerDetails table' 
    ELSE 
     SELECT 'ERROR: Expected 1 record in CustomerDetails table, but found ' + CONVERT(varchar(3), @Count) + ' records.' 


    SET @Count = (SELECT Count(*) 
        FROM CustomerProduct WITH (NOLOCK) 
        WHERE CustomerID = @CustomerID AND 
          DATEDIFF(mi, LastUpdatedAt, GETDATE()) < @MinsBack) 
    IF (@Count = 1) 
     SELECT 'Ok: 1 record in CustomerProduct table' 
    ELSE 
     SELECT 'ERROR: Expected 1 record in CustomerProduct table, but found ' + CONVERT(varchar(3), @Count) + ' records.' 

    SELECT *FROM Customer where customerID = @CustomerID 

END 

回答

1

建議您可以在您的SQL腳本中創建一個用作臨時存儲的臨時表。

CREATE TABLE #Results 
(
    Message VARCHAR(512) 
) 

而不是在每個IF直接SELECTELSE你應該插入串入臨時表。 在最後你可以達到你的目標是讓所有插入的字符串由返回他們:

SELECT * FROM #Results 

得到客戶 - 就像你在做到底 - 你應該觸發一個新的查詢數據庫。

根據您的情況,您應該考慮通過數據上下文查詢數據庫,而不是通過存儲過程查詢數據庫。

1

你需要做的是在本link建議,但我總結如下

對於每個結果集,你需要做一個reader.NextResult();

var someReturnObject = new ResultObject(); 

using (var context = new LinqPadDbContext(@"Server=localhost\SQLEXPRESS;Database=StackOverflow;Trusted_Connection=True;")) 
{ 
    var cmd = context.Database.Connection.CreateCommand(); 
    cmd.CommandText = "[dbo].[GetSomeData]"; 

    try 
    {   
     context.Database.Connection.Open(); 

     var reader = cmd.ExecuteReader(); 

     var result1 = ((IObjectContextAdapter)context).ObjectContext.Translate<string>(reader); 

     someResultObject.Text1 = result1.First(); 

     //for each extra result, start here 
     reader.NextResult(); 

     var users = ((IObjectContextAdapter)context).ObjectContext.Translate<User>(reader); 

     someResultObject.Users = users.Select(x => x); 
     //stop here 
    } 
    finally 
    { 
     context.Database.Connection.Close(); 
    } 
} 
+0

結合其他答案只需要處理兩個輸出。 –