我想更新表格中的字段,并在另一个表格中插入有关在我的网站中登录成功的用户的一些信息。 这是我的代码:
public class CustomerModels:ItemEntityDataContext
{
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(Customer c)
{
c.LastWebLogIn = DateTime.Now;
String ipAddress = System.Web.HttpContext.Current.Request.UserHostAddress;
WebsiteTracking web_track = new WebsiteTracking();
web_track.IDUser = c.ID;
web_track.ActiveLoginDate = DateTime.Now;
web_track.IPAddress = ipAddress;
this.DataContext.SaveChanges();
}
}
当我写这篇文章时,它只修改Customer表中的LastWebLogIn字段,但不会插入表WebsiteTracking中的字段。
任何人都可以解决这个问题?感谢。
答案 0 :(得分:1)
您可能希望将已创建的WebsiteTracking
添加到集合this.DataContext.WebsiteTracking
。其他方法是使用WebsiteTracking
对象的User
属性。在您使用其中一个之前,DataContext对web_track
对象一无所知。
public void UpdateCustomerLastUpdateStatus(Customer c)
{
c.LastWebLogIn = DateTime.Now;
String ipAddress = System.Web.HttpContext.Current.Request.UserHostAddress;
WebsiteTracking web_track = new WebsiteTracking();
web_track.ActiveLoginDate = DateTime.Now;
web_track.IPAddress = ipAddress;
c.WebsiteTracking.Add(web_track);
this.DataContext.SaveChanges();
}
答案 1 :(得分:1)
将Linq中的对象更新为SQL:
检查修改后的代码。 您可以一次更新多个对象,但必须注意对象/实体类创建的外键关系/或规则。
public void UpdateCustomerLastUpdateStatus(Customer c)
{
using ( var context = new this.DataContext())
// if you have created object on page then it may no need to create object again for DataContext
{
Customer cust = DataContext.Customer.Single(cu => cu.ID == c.ID);
// Validate cust that your Customer Id if it is supposed to be null reference issue.
cust.LastWebLogIn = DateTime.Now;
String ipAddress = System.Web.HttpContext.Current.Request.UserHostAddress;
WebsiteTracking web_track = new WebsiteTracking();
web_track.ActiveLoginDate = DateTime.Now;
web_track.IPAddress = ipAddress;
cust.WebsiteTracking.Add(web_track);
//or
DataContext.WebsiteTracking.Add(web_track);
this.DataContext.SaveChanges();
}
}