我有一个非常具体的问题。
以下是两个模型appointments.cs
和valid_clients.cs
。这两个模型都映射到两个数据库表。
appointmnets.cs
。它引用 valid_clients.cs
public partial class appointments
{
public int appt_client_id { get; set; }
public int customer_id { get; set; }
[Key]
public int appt_id { get; set; }
public DateTime appt_date_time { get; set; }
[ForeignKey("appt_client_id")]
public virtual valid_clients Client { get; set; }
}
valid_clients.cs
public partial class valid_clients
{
[Key]
public int client_id { get; set; }
[Required]
[StringLength(30)]
public string client_name { get; set; }
public bool valid_client { get; set; }
}
现在,我需要更新数据库中appointments
表中的单个记录。我在控制器方法中有以下代码用于更新。但此代码也在valid_clients
表中插入新记录,然后在appointments
中插入新记录。
[HttpPost]
public ActionResult Confirm1(appointments appointment,string submit)
{
using (var db1 = new appointmentContext()){
appointments app = db1.appointments.Single(d => d.appt_id == appointment.appt_id);
app = appointment;
app.appt_status = "RESCHED";
app.time_stamp = DateTime.Now;
//Saving the changes in the database
try
{
db.appointments.Add(app);
db.SaveChanges();
}
catch (System.Data.Entity.Validation.DbEntityValidationException e)
{
}
}
return View("Edit", appointment);
}
问题:
如何保持模型结构相同,只需更新appointments
表中的单个记录,而无需修改valid_clients
表。
答案 0 :(得分:0)
您的代码会创建一个新的appointments
。它不会更新现有的。
如果您想更新模型,可以执行以下操作:
appointments app = db1.appointments.Single(d => d.appt_id == appointment.appt_id);
app.appt_status = "RESCHED";
app.time_stamp = DateTime.Now;
app.OtherValue = appointment.OtherValue;
db.SaveChanges();
你忽略了这些界限:
app = appointment;
db.appointments.Add(app);
app = appointment;
实际上并未编辑您选择的appointments
。它只是将app
更改为指向另一个。
db.appointments.Add(app);
添加了一个新行,似乎并不是您需要的。