难以使用WebMatrix显示行数

时间:2012-05-15 13:14:41

标签: c# .net sql-server razor webmatrix

我有以下代码:

@helper RetrievePhotoWithName(int userid)
{
    var database = Database.Open("SC");
    var name = database.QuerySingle("select FirstName, LastName, ProfilePicture from UserProfile where UserId = @0", userid);
    var notifications =  database.Query("SELECT COUNT(*) FROM NotificationsTable WHERE UserID = @0 AND MessageWasRead = @1", userid, false);

    var DisplayName = "";
    if(notifications < 1)
    {
        DisplayName = name["FirstName"] + " " + name["LastName"];
    }
    else
    {
        DisplayName = name["FirstName"] + ", you have " + notifications + " new messages.";
    }
    <a href="@Href("~/Home")" title="My Account"><img src="@Href("~/Shared/Assets/Images/" + name["ProfilePicture"] + ".png")" id="MiniProfilePicture" />&nbsp;@DisplayName</a>

    database.Close();
}

应该计算我表中的所有行,并显示&#34;新通知&#34;在网页上向用户发送消息或仅显示他们的姓名,但它不起作用。

请勿编辑此问题。我重新发布这个问题的原因是因为我之前的问题被更改了,导致回复不准确。

2 个答案:

答案 0 :(得分:4)

由于SELECT COUNT(*)返回单个标量值,我认为您想要使用database.QueryValue()代替:

int notifications =  (int)database.QueryValue("SELECT COUNT(*) FROM NotificationsTable WHERE UserID = @0 AND MessageWasRead = @1", userid, false);

http://msdn.microsoft.com/en-us/library/webmatrix.data.database.queryvalue(v=vs.99).aspx

答案 1 :(得分:2)

试试这样:

@helper RetrievePhotoWithName(int userid)
{
    var database = Database.Open("SC");
    var name = database.QuerySingle("select FirstName, LastName, ProfilePicture from UserProfile where UserId = @0", userid);
    var notifications =  database.Query("SELECT convert(int,COUNT(*)) as 'counter' FROM NotificationsTable WHERE UserID = @0 AND MessageWasRead = @1", userid, false);

    var DisplayName = "";
    if(notifications["counter"] < 1)
    {
        DisplayName = name["FirstName"] + " " + name["LastName"];
    }
    else
    {
        DisplayName = name["FirstName"] + ", you have " + notifications["counter"] + " new messages.";
    }
    <a href="@Href("~/Home")" title="My Account"><img src="@Href("~/Shared/Assets/Images/" + name["ProfilePicture"] + ".png")" id="MiniProfilePicture" />&nbsp;@DisplayName</a>

    database.Close();
}