2016-05-12 106 views
0

是否可以從SP返回自定義表。我使用EF代碼第一種方法。從Ef代碼優先存儲Procdure中返回自定義表

這是我的SP

CREATE PROCEDURE [dbo].[GetUserNotification] 
    @ToUserId INT 
AS 
BEGIN 
select TU.FullName as ToUserName, 
     FU.FullName as FromUserName, 
     N.NotificationClickType, 
     N.TemplateId, 
     J.Title as JobTitle, 
     J.Identifier as JobIdentifier, 
     B.Identifier as BidIdentifier 
     from Notification N 
     inner Join AppUser TU on TU.Identifier = N.ToUserId 
     inner Join AppUser FU on FU.Identifier = N.FromuserId 
     inner Join Bid B on B.Identifier = N.NotificationBidId 
     inner Join Job J on J.Identifier = B.JobId 
     where [email protected] 
     Order By N.Identifier DESC 
END 

我的自定義視圖模型

public class NotificationModel 
    { 
     public string ToUserName { get; set; } 

     public string FromUserName { get; set; } 

     public NotificationClickType NotificationClickType { get; set; } 

     public int TemplateId { get; set; } 

     public string JobTitle { get; set; } 

     public int JobIdentifier { get; set; } 

     public int BidIdentifier { get; set; } 
    } 

我創建相同的視圖模型。但是我見過的每一處使用SP我只能返回我在DbContext類中添加的單個表數據。

回答

0

當您將存儲過程添加到EF模型時,它會自動創建一個複雜類型。 (至少它爲我做了,使用Model First)。

複合類型的名稱是添加了「_Result」的SP名稱,例如, GetUserNotification_Result。

可以使用複雜的類型,如:

using (Entities dbContext = new Entities()) 
{ 
    List<GetUserNotification_Result > data = dbContext.GetUserNotification(userId).ToList(); 
} 

另外,https://msdn.microsoft.com/en-us/data/jj691402.aspx展示瞭如何先用代碼。 How to call Stored Procedure in Entity Framework 6 (Code-First)?也可能有幫助。

+0

但我先使用代碼。我根本沒有edmx文件。如何將我的SP添加到我的上下文類。 – Programmer

+0

@程序員 - 請參閱我編輯的答案。 –