添加新的數據我有StudentRegistration模型類如下更新數據庫 - 刪除現有的數據和的EntityFramework
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列表和添加新list.The new studentreceipt list
在數據庫中適當添加但是existing studentreceipt list
未從數據庫中刪除,並且existing studentreceipt list
的StudentRegistrationId
設置爲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);
}
}
}
正如我新studentreceipt列表上面提到的在數據庫中適當添加,但現有的studentreceipt列表中,無法從現有.Infact名單studentreceipt的StudentRegistrationId設置爲null數據庫中刪除。 – ksg
那麼'_dbRegn.StudentReceipts.ToList()'中有沒有'StudentReceipts'? –
是的,在'_dbRegn.StudentReceipts.ToList()'中會有'StudentReceipts'。並且我想刪除現有的列表並添加新的列表 – ksg