1

在下面的代码中,我正在尝试为我的设施表添加一个新设施。“保存”方法调用 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; }
        }
4

2 回答 2

3

问题在这里:

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

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

_db.Facilities.Add(newFacility);
于 2013-05-16T15:06:07.743 回答
1

改变

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

_db.Facilities.Add(newFacility);

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

于 2013-05-16T15:05:10.940 回答