我有StudentRegistration Model Class如下
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; }
}
我试图删除现有的studentreceipt列表并添加新列表。new studentreceipt list
正在数据库中正确添加,但existing studentreceipt list
未从数据库中删除StudentRegistrationId
existing studentreceipt list
设置为null
。
我想从数据库中删除现有的studentreceipt list
并添加新列表。我该怎么办?
这就是我试过的
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);
}
}
}
答案 0 :(得分:1)
您可以尝试如下所示。
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())
{
__db.StudentReceipts.Remove(_existingReceipt);
}
//adding new receipt
foreach (var _receipt in mdlCourseInterchange.StudentReceiptList)
{
StudentReceipt _studReceipt = new StudentReceipt();
//...
//...
_db.StudentReceipts.Add(_studReceipt);
}
//...
//..
int j = _db.SaveChanges();
if (j > 0)
{
_ts.Complete();
return Json(new { message = "success" }, JsonRequestBehavior.AllowGet);
}
}
}