创建一个新实体并调用SaveChanges将其保存回数据库MVC

时间:2013-05-16 15:02:37

标签: asp.net-mvc

在下面的代码中,我正在尝试新设施到我的设施表。 “Save”方法调用DbContext SaveChanges()。在SaveChanges()执行之后,我希望newFacility为它生成一个Id,但它不会,它也不会保存到数据库中。我可能会在设施DbSet中添加新设施的方式出现问题吗?

[HttpPost]
            public ActionResult Create(CreateFacilityViewModel viewModel)
            {
                if (ModelState.IsValid)
                {
                    var facilities = _db.Facilities;
                    var newFacility = new Facility();

                    //newFacility.FacilityId = viewModel.FacilityId;
                    newFacility.FaclityName = viewModel.FaclityName;
                    newFacility.Address = viewModel.Address;
                    newFacility.City = viewModel.City;
                    newFacility.State = viewModel.State;

                    _db.Facilities.ToList().Add(newFacility);

                    _db.Save();

                    return RedirectToAction("detail", "facility", new { id = newFacility.FacilityId });
                }
                return View(viewModel);
            }

设施看起来像..

 public DbSet<Facility> Facilities { get; set; }
  IQueryable<Facility> IGolfDataSource.Facilities
        {
            get { return Facilities; }
        }

2 个答案:

答案 0 :(得分:3)

问题在于:

_db.Facilities.ToList().Add(newFacility);

当您调用ToList时,它会在内存中创建一个新列表,然后您将新设施添加到内存列表中的新列表中。相反,您希望将新Facility直接添加到DbSet中:

_db.Facilities.Add(newFacility);

答案 1 :(得分:1)

更改

_db.Facilities.ToList().Add(newFacility);

_db.Facilities.Add(newFacility);

您希望将对象添加到上下文,而不是列表。