不确定如何短语:重写教程中的方法

时间:2012-02-13 19:34:46

标签: c# asp.net asp.net-mvc asp.net-mvc-3

我正在尝试创建自定义MembershipUser,我必须覆盖GetUser()方法。

我正在关注本教程:http://msdn.microsoft.com/en-us/library/ms366730.aspx

这就是我所拥有的:

    public override MembershipUser GetUser(string username, bool userIsOnline)
    {
        CustomMembershipConext db = new CustomMembershipConext();

        var user = db.User.Where(u => u.UserName == username).FirstOrDefault();

        if (userIsOnline)
        {
            user.LastActivityDate = DateTime.Now;

        }

        return user;
        // Error 4 Cannot implicitly convert type 'MvcApplication1.Models.User' to 'System.Web.Security.MembershipUser'

    }
}

我试图复制这个:

public override MembershipUser GetUser(string username, bool userIsOnline)
{
   OdbcConnection conn = new OdbcConnection(connectionString);
   OdbcCommand cmd = new OdbcCommand("SELECT PKID, Username, Email, PasswordQuestion," +
        " Comment, IsApproved, IsLockedOut, CreationDate, LastLoginDate," +
        " LastActivityDate, LastPasswordChangedDate, LastLockedOutDate," +
        " IsSubscriber, CustomerID" +
        " FROM Users  WHERE Username = ? AND ApplicationName = ?", conn);

  cmd.Parameters.Add("@Username", OdbcType.VarChar, 255).Value = username;
  cmd.Parameters.Add("@ApplicationName", OdbcType.VarChar, 255).Value = pApplicationName;

  OdbcMembershipUser u = null;
  OdbcDataReader reader = null;

  try
  {
    conn.Open();

    reader = cmd.ExecuteReader();

    if (reader.HasRows)
    {
      reader.Read();
      u = GetUserFromReader(reader);

      if (userIsOnline)
      {
        OdbcCommand updateCmd = new OdbcCommand("UPDATE Users  " +
                  "SET LastActivityDate = ? " +
                  "WHERE Username = ? AND Applicationname = ?", conn);

        updateCmd.Parameters.Add("@LastActivityDate", OdbcType.DateTime).Value = DateTime.Now;
        updateCmd.Parameters.Add("@Username", OdbcType.VarChar, 255).Value = username;
        updateCmd.Parameters.Add("@ApplicationName", OdbcType.VarChar, 255).Value = pApplicationName;

        updateCmd.ExecuteNonQuery();
      }
    }

  }
  catch (OdbcException e)
  {
    if (WriteExceptionsToEventLog)
    {
      WriteToEventLog(e, "GetUser(String, Boolean)");

      throw new ProviderException(exceptionMessage);
    }
    else
    {
      throw e;
    }
  }
  finally
  {
    if (reader != null) { reader.Close(); }

    conn.Close();
  }

  return u;      
}

1 个答案:

答案 0 :(得分:1)

用户不是Type用户,它仍然是IQueryable< ...&gt ;.您需要从查询结果中提取用户对象:

var user = db.User.Where(u => u.UserName == username).FirstOrDefault();