我想记录登录我网站的用户的上次更新。登录成功后,laseUpdate字段必须更改为当前日期时间。
我使用了这段代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace ICEWeb.Models
{
public class CustomerModels:ItemEntityDataContext
{
public bool ValidateCustomer(string username, string password)
{
bool b = (
this.DataContext
.Customers
.Where(s => s.ActiveInWebLogin == 1
&&
s.WebAccount == username
&&
s.Password == password
)
.SingleOrDefault()
) != null;
if (b == true)
this.UpdateCustomerLastUpdateStatus();
return b;
}
public void UpdateCustomerLastUpdateStatus()
{
Customer c = new Customer();
c.LastWebLogIn = DateTime.Now;
this.DataContext.SaveChanges();
}
}
}
validateCustomer()正常工作,但它没有更新我的记录(LastWebLogIn)。 有人能为我解决这个问题吗? 感谢。
答案 0 :(得分:1)
您不应该创建新实例,而应该是Customers对象的当前实例并将其更新到数据库。尝试这样的事情:
public bool ValidateCustomer(string username, string password)
{
var user = this.DataContext.Customers
.Where(s => s.ActiveInWebLogin == 1 &&
s.WebAccount == username &&
s.Password == password)
.SingleOrDefault();
if (user != null)
{
this.UpdateCustomerLastUpdateStatus(user);
return true;
}
return false;
}
public void UpdateCustomerLastUpdateStatus(Customers c)
{
c.LastWebLogIn = DateTime.Now;
this.DataContext.SaveChanges();
}
答案 1 :(得分:0)
您正在为身份不明的新客户设置LastWebLogIn
。从数据库中获取客户(根据您的第一种方法),并更新该对象(确保您没有使用只读数据上下文进行优化)。
答案 2 :(得分:0)
如果您想创建新客户,请使用Table.InsertOnSubmit Method:
var customer = new Customer();
customer.LastWebLogIn = DateTime.Now;
this.DataContext.Customers.InsertOnSubmit(customer);
this.DataContext.SubmitChanges();
如果您想更新现有客户,请执行以下操作:
var customer = this.DataContext.Customers
.Where(...)
.Single();
customer.LastWebLogIn = DateTime.Now;
this.DataContext.SaveChanges();
答案 3 :(得分:0)
您可以尝试以下代码:
public bool ValidateCustomer(string username, string password)
{
var customer = this.DataContext
.Customers
.Where(s => s.ActiveInWebLogin == 1
&&
s.WebAccount == username
&&
s.Password == password
)
.SingleOrDefault()
if (customer != null)
return this.UpdateCustomerLastUpdateStatus(customer);
return false;
}
public void UpdateCustomerLastUpdateStatus(Customer c)
{
try
{
c.LastWebLogIn = DateTime.Now;
this.DataContext.SaveChanges();
return true;
}
Catch(Exception ex)
{
// Log the error
return false;
}
}