Click here to Skip to main content
15,884,628 members
Articles / Web Development / ASP.NET
Tip/Trick

Inserting Data into Multiple Tables using Code First Approach and ViewModel

Rate me:
Please Sign up or sign in to vote.
4.36/5 (10 votes)
10 Sep 2013CPOL1 min read 66K   13   10
How to insert data to multiple tables using the Code First approach.

Introduction

In this article, I am going to explain how to insert data to multiple tables using the Code First approach.

Let’s begin with the View Model.

What is ViewModel?

ViewModel in MVC design pattern is very similar to 'model'. The major difference between 'Model' and ‘ViewModel’ is that we use ViewModel only in rendering views.

Start with a small example

Let’s assume we want to implement a view that will have five textboxes for UserName, Password, RePassword, Address, and Email.

Now, I want to store UserName and Password into the Login table and UserName, Address, and Email into the User table. I want to insert the data into these two tables from a single view. For this I am taking advantage of the ViewModel to render all controls in a single view.

Let’s begin with creating the Model.

C#
public class Login
{
    [Key]
    public String Username { get; set; }
    [DataType(DataType.Password)]
    public String Password { get; set; }
}
public class User
{
    [Key]
    public string Username { get; set; }
    public string Address { get; set; }
    public string Email { get; set; }
}

Let’s create the View Model to render the controls in the view:

C#
public class LoginViewModel
{
    public String Username { get; set; }
    [DataType(DataType.Password)]
    public String Password { get; set; }
    [DataType(DataType.Password)]
    public String RePassword { get; set; }
    public String Address { get; set; }
    public string Email { get; set; }
}

Let’s add LoginDBContext:

C#
public class LoginDBContext : DbContext
{
    public DbSet<Login> logins { get; set; }
    public DbSet<User> user { get; set; }
}

We are done with creating Model classes.

Let’s create the Controller and name it Login.

Image 1

Add the following code inside the controller.

C#
LoginDBContext db = new LoginDBContext();
//
// GET: /Login/

public ActionResult Index()
{
    
    return View();
}
public ActionResult Login()
{
    return View();
}
[HttpPost]
public ActionResult Login(LoginViewModel viewModel)
{
         var login = new Login()
    {
        Username = viewModel.Username,
        Password = viewModel.Password
    };

    var user = new User()
    {
        Username=viewModel.Username,
        Address=viewModel.Address,
        Email=viewModel.Email
       
    };
    db.logins.Add(login);
    db.user.Add(user);
    db.SaveChanges();
    return View();
}

We are done with creating the Controller, let's create a view. Right-click on Login, Add View.

Image 2

Login view will be generated for us.

XML
@model MvcViewModel.Models.LoginViewModel

@{
    ViewBag.Title = "Login";
}

<h2>Login</h2>

@using (Html.BeginForm()) {
    @Html.ValidationSummary(true)

    <fieldset>
        <legend>LoginViewModel</legend>

        <div class="editor-label">
            @Html.LabelFor(model => model.Username)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Username)
            @Html.ValidationMessageFor(model => model.Username)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.Password)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Password)
            @Html.ValidationMessageFor(model => model.Password)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.RePassword)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.RePassword)
            @Html.ValidationMessageFor(model => model.RePassword)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.Address)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Address)
            @Html.ValidationMessageFor(model => model.Address)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.Email)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.Email)
            @Html.ValidationMessageFor(model => model.Email)
        </div>    

        <p>
            <input type="submit" value="Create" />
        </p>
    </fieldset>
}

<div>
    @Html.ActionLink("Back to List", "Index")
</div>

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}

Finally the rendered view will look like this:

Image 3

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



Comments and Discussions

 
Questionforeign key relation Pin
Member 1196206419-Sep-15 3:40
Member 1196206419-Sep-15 3:40 
BugHow to Delete Data in a single view from Multiple Tables in MVC Pin
Member 119620647-Sep-15 8:26
Member 119620647-Sep-15 8:26 
QuestionNice Artcle Pin
Dev Anil Seema22-Sep-14 1:57
Dev Anil Seema22-Sep-14 1:57 
GeneralMy vote of 3 Pin
Member 107674598-Jun-14 10:20
Member 107674598-Jun-14 10:20 
QuestionThe best overloaded method match for 'System.Data.Entity.DbSet<AnfhdMvcApp.Voucher_Master>.Add(AnfhdMvcApp.Voucher_Master)' has some invalid arguments Pin
Member 107674598-Jun-14 10:16
Member 107674598-Jun-14 10:16 
QuestionError : An exception occurred while initializing the database. See the InnerException for details. Pin
P@-Earth23-May-14 1:57
P@-Earth23-May-14 1:57 
GeneralMy vote of 5 Pin
Member 107159401-Apr-14 4:44
Member 107159401-Apr-14 4:44 
QuestionEdit Pin
Jeremy Hutson29-Oct-13 11:55
Jeremy Hutson29-Oct-13 11:55 
GeneralMy vote of 5 Pin
Nandakishore G N11-Sep-13 0:36
professionalNandakishore G N11-Sep-13 0:36 
GeneralMy vote of 3 Pin
Member 1019188010-Sep-13 19:15
Member 1019188010-Sep-13 19:15 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.