0

我有以下代码:

@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();
}

这应该计算我表中的所有行,并在网页上向用户显示“新通知”消息,或者只显示他们的名字,但它不起作用。

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

4

2 回答 2

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

于 2012-05-15T13:21:31.610 回答
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();
}
于 2012-05-15T13:23:33.133 回答