How To Scaffold a View Model in MVC 5

随声附和 提交于 2021-02-16 04:53:31

问题


I'm trying to work on a simple application. I have three SQL tables brought in through Entity Framework and had the models created automatically. I want to be able to scaffold out the Create/Details/Edit etc. views automatically in Visual Studio. I can do this automatically when I scaffold from a single model (like Name alone), but can't get anywhere when using a View Model as a source.

Here are my models

Name

public partial class Name
{
    public Name()
    {
        this.Addresses = new HashSet<Address>();
        this.Emails = new HashSet<Email>();
    }

    public int ID { get; set; }
    public string FIRST_NAME { get; set; }
    public string LAST_NAME { get; set; }

    public virtual ICollection<Address> Addresses { get; set; }
    public virtual ICollection<Email> Emails { get; set; }
}

Address

public partial class Address
{
    public int ADDRESS_ID { get; set; }
    public int NameID { get; set; }
    public string ADDRESS_1 { get; set; }
    public string CITY { get; set; }
    public string STATE { get; set; }
    public string ZIP { get; set; }

    public virtual Name Name { get; set; }
}

Email

public partial class Email
{
    public int EMAIL_ID { get; set; }
    public int NameID { get; set; }
    public string EMAIL { get; set; }

    public virtual Name Name { get; set; }
}

and a View Model I created of all three

public class MainVM
{
    public Name Name { get; set; }
    public Address Address { get; set; }
    public Email Email { get; set; }
}

I can go through the steps of creating a controller - Right click Controllers >> Add >> Controller >> MVC 5 Controller with views, using Entity Framework.

Next I get to this screen.

enter image description here

If I click Add, I will get the following error.

enter image description here

I've read in other answers that you need to clear out the Data context class (from the first image) if you are using a View Model, but if I do that, the Add button becomes deactivated. I can't go further than that. Any ideas here?


回答1:


I bet the original poster might not still be looking for an answer by this time. but it can help seekers like me..

Found this article be of some help. Link

It seems while taking the route Controller -> Add -> New Scaffolded Item -> MVC Controller with views, using Entity Framework does not work well with view models.

If you did not provide a DataContext class in the above mentioned scaffolding process while selecting your viewmodel, MVC scaffolding will not allow you to proceed further. As you indicated the "Add" button is disabled.

The workaround is to take a two step approach.

First create controller actions using scaffolding (Controllers -> Add -> New Scaffolded Item -> MVC Controller with read/write actions)

And then add views by right clicking on individual controller action methods and then taking advantage of scaffolding. (Controller's Action method -> Right click -> Add View -> Template -> [choose anything but Empty(without model)] -> Model class -> [choose your view model here] -> Leave Data context class empty -> Add button will now be enabled).

The linked article covers the steps in detail please take a look.

However, you will still need to add code yourself to work with the database using Entity framework in your controller action methods. (Or you can choose to introduce Busines layers, repositories etc.. YMMV) But this helps avoid writing lots of code to create your views.

PS: I found this approach work just fine for me while using ASP.Net core 1.1




回答2:


I tried to use a View Model in a controller and got the same error. I then added an ID Key to solve the error and EF made a table representing the View Model in my database. With that I concluded that View Models are not to know anything about the database and are only used for presentation in the View. In the controller I handled the database operations for the different entities.

I had to create a view manually and use @model myproject.ViewModels.MyViewModel in the View to represent the View Model for the Html helpers.

This process worked for me and I was able to save the information to the proper database tables per entity model.

The following code is an example. You could use mapping tool instead of manually typing the code. Breaking the viewmodel up into the entities to save using Entity Framework.

 public ActionResult EmployeeDepartment(EmployeeViewModel evm)
    {
        if(ModelState.IsValid)
        {
            try
            {

                Department dept = new Department();
                dept.DepartmentName = evm.DepartmentName;
                dept.DepartmentNumber = evm.DepartmentNumber;

                db.Departments.Add(dept);
                db.SaveChanges();

                Employee emp = new Employee();

                emp.FirstName = evm.FirstName;
                emp.LastName = evm.LastName;
                emp.Department = dept;

                db.Employees.Add(emp);
                db.SaveChanges();

                return RedirectToAction("Index");
            }
            catch(Exception ex)
            {
                //write code for exception
            }
        }
            return View();


    }



回答3:


Keep data context class empty and then try to add the view. It worked for me. Also, add [Key] to any id attribute.



来源:https://stackoverflow.com/questions/29828936/how-to-scaffold-a-view-model-in-mvc-5

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!