我有一个存储过程如下。请参阅第1行/第2行用于设置datacontext。我从这里的一个帖子中读到了这个。在我的C#代码中,我按如下方式调用此存储过程。我可以在数据库中看到存储过程的结果。我可以在数据库中看到2条结果记录。
但是从下面的C#代码调用返回计数2,但两个记录都为null和0。请帮忙。
public class UnreadAlerts
{
public string alertName { get; set; }
public int alertValue { get; set; }
}
public List<UnreadAlerts> AllUnreadAlertsCount(int userId)
{
List<UnreadAlerts> Sdetails = new List<UnreadAlerts>();
using (var context1 = new AltusEntities())
{
Sdetails = context1.Database.SqlQuery<UnreadAlerts>("[dbo].[sp_UnreadAlertsCount] @userid",
new SqlParameter("@userid", userId)
).ToList();
}
return Sdetails;
}
存储过程代码:
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER Procedure [dbo].[sp_UnreadAlertsCount]
@userId int
AS
BEGIN
IF 1 = 2
BEGIN
SELECT
cast(null as nvarchar(50)) as Aname
,cast(null as int) as Avalue
WHERE
1 = 2
END
CREATE TABLE #Results
(
Aname nvarchar(50),
Avalue int
)
INSERT INTO #Results (Aname, Avalue)
SELECT
'ProximityAlerts',
COUNT(DISTINCT ProximityMeetingAlertID)
FROM
AltusRt.dbo.ProximityMeetingAlerts pma
JOIN
AltusRt.dbo.ProximityMeetings pm ON pma.ProximityMeetingID = pm.ProximityMeetingID
WHERE
pm.RequestID IN (SELECT r.RequestId
FROM Users u
JOIN Requests r ON u.UserId = r.CreatedByUserId
WHERE u.UserId = @userId
AND r.CreatedByUserId = @userId)
INSERT INTO #Results (Aname,Avalue)
SELECT
'MonitorAlerts',
COUNT(*)
FROM
dbo.TargetGeoFenceResult
WHERE
ActiveStatus = 1
SELECT Aname, Avalue
FROM #Results
END
答案 0 :(得分:1)
列名称和属性名称不匹配。因此,这些值永远不会复制到UnreadAlerts
实例,并且您会看到默认值int
和string
。
现在您可以通过更改属性名称来修复它:
public class UnreadAlerts
{
public string Aname{ get; set; }
public int Avalue { get; set; }
}
或者,使用[ColumnAttribute]
:
public class UnreadAlerts
{
[Column(Name = "Aname")]
public string alertName { get; set; }
[Column(Name = "Avalue")]
public int alertValue { get; set; }
}