I have StudentRegistration Model Class as follows
public partial class StudentRegistration
{
public StudentRegistration()
{
this.StudentReceipts = new HashSet<StudentReceipt>();
}
public int Id { get; set; }
public Nullable<int> StudentWalkInnID { get; set; }
...
...
public virtual ICollection<StudentReceipt> StudentReceipts { get; set; }
}
public partial class StudentReceipt
{
public int Id { get; set; }
public Nullable<int> StudentRegistrationID { get; set; }
...
...
public virtual StudentRegistration StudentRegistration { get; set; }
}
I was trying to delete existing studentreceipt list and add new list.The new studentreceipt list is adding properly in the database but the existing studentreceipt list is not getting deleted from the database and the StudentRegistrationId of existing studentreceipt list is set to null.
I want to delete the existing studentreceipt list from the database and add new list.How can I do it ?
This is what I have tried
using (TransactionScope _ts = new TransactionScope())
{
_dbRegn = _db.StudentRegistrations
.Where(r => r.Id == Id).FirstOrDefault();
if (_dbRegn != null)
{
//Remove existing receipts
foreach (var _existingReceipt in _dbRegn.StudentReceipts.ToList())
{
_dbRegn.StudentReceipts.Remove(_existingReceipt);
}
//adding new receipt
foreach (var _receipt in mdlCourseInterchange.StudentReceiptList)
{
StudentReceipt _studReceipt = new StudentReceipt();
//...
//...
_dbRegn.StudentReceipts.Add(_studReceipt);
}
//...
//..
db.Entry(_dbRegn).State = EntityState.Modified;
int j = _db.SaveChanges();
if (j > 0)
{
_ts.Complete();
return Json(new { message = "success" }, JsonRequestBehavior.AllowGet);
}
}
}
StudentReceiptsin_dbRegn.StudentReceipts.ToList()?StudentReceiptsin_dbRegn.StudentReceipts.ToList().And I want to delete the existing list and add the new list_dbRegn = _db.StudentRegistrations.Where(r => r.Id == Id).FirstOrDefault();you are not including theStudentReceiptslist property. So you are removing nothing.virtual keywordforStudent Receipt Collection.So I thinkincludeis not required here