我正在尝试使用asp.net mvc 4
& EF6
我要更新记录并使用更新记录中的值将新记录添加到另一个模型。到目前为止,我可以更新现有记录,但是当系统尝试将新记录添加到另一个模型时,我在控制器中出现错误。错误是,
对象引用未设置为对象的实例。
以下是我的代码,
控制器
[HttpPost]
public ActionResult RentController(FlatModel flatId)
{
if (Session["AdminNAME"] != null)
{
if (ModelState.IsValid)
{
var dbPost = rentdb.FlatInfoes.Where(p => p.flatno == flatId.Flats.flatno).FirstOrDefault();
if (dbPost == null)
{
return RedirectToAction("RentController");
}
dbPost.flat_owner_name = flatId.Flats.flat_owner_name;
dbPost.flat_owner_phone = flatId.Flats.flat_owner_phone;
var addRentSchedule = flatId.BillCheck;
addRentSchedule.fullname = flatId.Flats.flat_owner_name; //error showing in this line.
addRentSchedule.isRented = "N";
addRentSchedule.due = 10000;
DateTime today = DateTime.Now;
DateTime newDay = today.AddDays(30);
addRentSchedule.submitTime = newDay;
rentdb.BillPayChecks.Add(addRentSchedule);
rentdb.SaveChanges();
TempData["flat_assign_success"] = "Information Updated Successfully!";
return RedirectToAction("RentController");
}
else
{
TempData["flat_assign_fail"] = "Error! Information update failed!";
return RedirectToAction("RentController");
}
}
else
{
return RedirectToAction("AdminLogin");
}
}
模型
public class FlatModel
{
public FlatInfo Flats { get; set; }
public BillPayCheck BillCheck { get; set; }
}
我在代码中做错了什么?更新模型时,如何从更新的值中添加记录?非常需要这个帮助。 TNX。
答案 0 :(得分:1)
这是对我的代码进行故障排除"类型问题,所以得到一个准确的答案将是艰难的。但是,看看这一行
var addRentSchedule = flatId.BillCheck;
让我觉得你得到了一个Null参考。您在此之后的行上看到错误,因为您正在尝试在null对象上设置属性。如果租金计划实际上是一个新的数据库记录,那么很可能,您需要创建一个新对象。因此,您的代码可能看起来像这样:
var addRentSchedule = new BillCheck();
//you need to tie this to the parent record using the parent record
//primary key and setting the BillCheck Foreign key appropriately
//since I dont know your db schema, I am guessing on this line.
addRentSchedule.flatId = flatId.Id;
addRentSchedule.fullname = flatId.Flats.flat_owner_name;
addRentSchedule.isRented = "N";
addRentSchedule.due = 10000;
//no point in creating variables when you can do it all in one line here.
addRentSchedule.submitTime = DateTime.Now.AddDays(30);
rentdb.BillPayChecks.Add(addRentSchedule);