不知道如何表达:重写教程中的方法
本文关键字:方法 教程 重写 何表达 不知道 | 更新日期: 2023-09-27 18:24:15
我正在尝试创建一个自定义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;
}
用户不是用户类型,它仍然是IQueryable<…>。您需要从查询结果中取出您的用户对象:
var user = db.User.Where(u => u.UserName == username).FirstOrDefault();