Reputation: 141
I have a HttpPost controller which adds a School model booking into the Schools Db (which saves info like School Name, School Date, School Id). Now I need to delete the row in Dates Db which Date is the same Date as the one just entered into School Db e.g. if School model date entered was 13/07/2019, I want to find the row in Dates Db which has the date - 13/07/2019 and then delete this row from the table
My controller so far:
[HttpPost]
public ActionResult Booking(School model)
{
db.Schools.Add(model);
db.SaveChanges();
//make chosen school date unavailable in datepicker
Datepicker date = db.Dates.Find(model.Date);
db.Dates.Remove(date);
db.SaveChanges();
return RedirectToAction("Booking");
}
School model (Schools Db context):
namespace BookingSys.Models
{
public class School
{
public DateTime Date { get; set; }
public int Id { get; set; }
public string Name { get; set; }
public string Email { get; set; }
public int PhoneNumber { get; set; }
}
}
DatePicker model (Dates Db context):
namespace BookingSys.Models
{
public class Datepicker
{
public DateTime Date { get; set; }
public int Id { get; set; }
public int LecturerId { get; set; }
public string Comment { get; set; }
}
}
I am currently getting the following error when I click submit in the View to create a School model:
System.ArgumentException: 'The type of one of the primary key values did not match the type defined in the entity. See inner exception for details. Parameter name: keyValues' EntitySqlException: The argument types 'Edm.Int32' and 'Edm.DateTime' are incompatible for this operation. Near WHERE predicate, line 1, column 62.
Thanks in advance
Upvotes: 0
Views: 355
Reputation: 1554
What you need is the lamda expression and also use First
or FirstOrDefault
change this line
Datepicker date = db.Dates.Find(model.Date);
To
Datepicker date = db.Dates.First(m => m.Date == model.Date);
OR
//if you are not sure if the date exists in both tables
Datepicker date = db.Dates.FirstOrDefault(m => m.Date == model.Date);
// then check for null before deleting
Find()
requires the value of the primary key of the table and you need to get the data bay Date
Upvotes: 1