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