目前正在教我如何使用MVC,我的主管向我展示了如何使用具有读取功能的存储库,但是我坚持实现Add函数。这是我当前的代码,谢谢!!
存储库:
public void AddDriver(DriverModel model)
{
using (var db = new VehicleReservationEntities())
{
var newDriver = new Driver();
newDriver.DriverLastName = model.DriverLastName;
newDriver.DriverFirstName = model.DriverFirstName;
newDriver.DriverLicense = model.DriverLicense;
newDriver.LicenseExpiry = model.LicenseExpiry;
newDriver.MobileNumber = model.MobileNumber;
newDriver.BusinessUnit = model.BusinessUnit;
newDriver.DateRegistered = model.DateRegistered;
db.Driver.Add(newDriver);
db.SaveChanges();
}
}
控制器:
public ActionResult Add()
{
var repo = new VehicleRepository();
var data = repo.AddDriver();
var DVM = new DriverViewModel();
DVM.DriverLastName = data.DriverLastName;
DVM.DriverFirstName = data.DriverFirstName;
DVM.DriverLicense = data.DriverLicense;
DVM.LicenseExpiry = data.LicenseExpiry;
DVM.MobileNumber = data.MobileNumber;
DVM.BusinessUnit = data.BusinessUnit;
DVM.DateRegistered = data.DateRegistered;
db.Driver.Add();
db.SaveChanges();
}
答案 0 :(得分:0)
您发布的内容似乎存在一些问题。我认为您正在寻找以下内容:
控制器:
[HttpPost]
public ActonResult Add(DriverViewModel DVM)
{
var repo = new VehicleRepository();
var driver = new Driver();
//tools such as automapper or tinymapper are often used so that you dont
//need to manually make these assignments
driver.DriverLastName = DVM.DriverLastName;
driver.DriverFirstName = DVM.DriverFirstName;
driver.DriverLicense = DVM.DriverLicense;
driver.LicenseExpiry = DVM.LicenseExpiry;
driver.MobileNumber = DVM.MobileNumber;
driver.BusinessUnit = DVM.BusinessUnit;
driver.DateRegistered = DVM.DateRegistered;
repo.AddDriver(driver);
//return whatever view you want to go to after the save
return View("Index");
}
存储库:
public void AddDriver(Driver newDriver)
{
using (var db = new VehicleReservationEntities())
{
db.Driver.Add(newDriver);
db.SaveChanges();
}
}
一些注意事项:通常,如果您使用的是ViewModel,则这些ViewModel会发布到控制器而不是原始EF实体。您还正在控制器和存储库中调用db.SaveChanges
,这似乎不是您想要的。 DbSet
通常也是复数的,因此您将驱动程序添加到数据库的调用看起来像db.Drivers.Add(newDriver)
。您还显示了与驱动程序相关的3个不同的类:Driver
,DriverModel
和DriverViewModel
。有时,如果您的体系结构将事物分为用于数据访问,业务逻辑和Web的多个不同层,则这很有必要,但是我在这里看不到任何证据。如果所有内容都存在于一个项目中,那么我可能会坚持使用DriverViewModel
和Driver
,其中Driver
是EF实体,而DriverViewModel
是您的视图使用并传递回控制器