使用存储库MVC添加/插入数据

时间:2018-06-29 16:47:50

标签: c# .net asp.net-mvc

目前正在教我如何使用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();
    }

1 个答案:

答案 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个不同的类:DriverDriverModelDriverViewModel。有时,如果您的体系结构将事物分为用于数据访问,业务逻辑和Web的多个不同层,则这很有必要,但是我在这里看不到任何证据。如果所有内容都存在于一个项目中,那么我可能会坚持使用DriverViewModelDriver,其中Driver是EF实体,而DriverViewModel是您的视图使用并传递回控制器