更新数据库 - 删除现有数据并使用entityframework添加新数据

时间:2016-10-19 14:04:28

标签: c# entity-framework asp.net-mvc-4 entity-framework-5

我有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);
    }
  }
}

1 个答案:

答案 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);
    }
  }
}