C# 在asp.net mvc中同时插入和修改两个不同的表
我想更新我的表中的字段,并在另一个表中插入有关成功登录我的网站的用户的信息。 这是我的代码:C# 在asp.net mvc中同时插入和修改两个不同的表,c#,asp.net,asp.net-mvc,linq-to-sql,C#,Asp.net,Asp.net Mvc,Linq To Sql,我想更新我的表中的字段,并在另一个表中插入有关成功登录我的网站的用户的信息。 这是我的代码: public class CustomerModels:ItemEntityDataContext { public bool ValidateCustomer(string username, string password) { var user = this.DataContext.Customers
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中的字段
谁能解决这个问题?谢谢。您可能需要将创建的
WebsiteTracking
添加到集合this.DataContext.WebsiteTracking
。另一种方法是使用User
对象的WebsiteTracking
属性。除非您使用其中一个,否则DataContext对web\u 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();
}
要将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();
}
}
web_track.User不起作用,因为它在我的表中不包含“User”的定义。OP说
c
是更新的,而不是创建的,所以使用c.ID
应该可以。这一行与您的错误:c.WebsiteTracking.Add(web_track);它应该有用。。当您传递customer对象时,就不需要从数据库访问。。我认为LInqtoSql文件可能存在一些问题。。在已创建的实体类中使用断点跟踪错误。。