我想删除传真表中的传真和FaxData中与传真表中具有相同传真ID的记录 我创建了viewmodel视图来连接2个表 使用System.Web.Mvc;
namespace FaxProject.ViewModel
{
public class SendFaxVm
{
public List<SelectListItem> Employees { set; get; }
public int[] SelectedEmployees { set; get; }
public Fax fax { set; get; }
public int FaxId { set; get; }
public string CompanyName { set; get; }
public int Courier_Num { set; get; }
public Nullable<int> NumberOfPages { get; set; }
public string CompanyAddress { get; set; }
public string ReceivingDate { get; set; }
public string Attachment { get; set; }
public string Subject { get; set; }
}
}
这是viewmodel
public ActionResult Delete(int id,SendFaxVm vm,Fax fax)
{
foreach (var userId in vm.SelectedEmployees)
{
var faxdatadelete = Db.FaxDatas.Single(f => f.FaxId == fax.Id);
Db.FaxDatas.Remove(faxdatadelete);
Db.SaveChanges();
}
var deletedfax = Db.Faxes.Single(f => f.Id == id);
Db.Faxes.Remove(deletedfax);
Db.SaveChanges();
return RedirectToAction("FaxForm", "Fax");
}
这是传真控制器中的动作..... 这是我尝试删除时遇到的异常(在FaxProject.dll中发生了'System.NullReferenceException'类型的异常,但未在用户代码中处理
附加信息:未将对象引用设置为对象的实例。)
答案 0 :(得分:-1)
应该是:
public ActionResult Delete(int id, SendFaxVm vm, Fax fax)
{
if (SendFaxVm == null || Fax == null)
{
return RedirectToAction("FaxForm", "Fax");
}
foreach (var userId in vm.SelectedEmployees)
{
var faxdatadelete = Db.FaxDatas.FirstOrDefault(f => f.FaxId == fax.Id);
if (faxdatadelete != null)
{
Db.FaxDatas.Remove(faxdatadelete);
Db.SaveChanges();
}
}
var deletedfax = Db.Faxes.FirstOrDefault(f => f.Id == id);
if (deletedfax != null)
{
Db.Faxes.Remove(deletedfax);
Db.SaveChanges();
}
return RedirectToAction("FaxForm", "Fax");
}