How to insert and display User and Address model using Entity Framework entity-framework-6


I want to display both user info and address model in the same view.

These are my code structures:

In Data Access Layer, I have model classes:


public class User
        public int UserId { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string RestaurantName { get; set; }
        public string PrimaryPhone { get; set; }    


public class Location
            public int Id { get; set; }
            public string Line1 { get; set; }
            public string Line2 { get; set; }
            public string City { get; set; }
            public string State { get; set; }
            public string Country { get; set; }
            public string ZipCode { get; set; }
            public User User { get; set; }

So, I have two separate repositories for user and address models which perform add and get all functions which is working perfectly fine.

Now, I want both of this model information should be displayed in the view at the same time.

How can I combine both in the same view. I'm unable to do it. I can do it, but the thing is both are displayed in separate views.

Any advice would be appreciated!

4/6/2017 4:48:35 AM

Accepted Answer

Use a ViewModel. Your ViewModel could look something like this:

public class MyViewModel
    public User UserVm {get;set;}
    public Location LocationVm {get;set;}

Use the MyViewModel in your view. Your controller will accept a MyViewModel object.

You can then pass the LocationVm and UserVm objects from your viewModel to your repository.

4/6/2017 5:27:10 AM

Popular Answer

Add One more Property To your User Model like below

-- Model Section

public class User
public List<Location> location {get;set;}

-- Controller Section

public ActionResult Index()
List<Location> loc= new List<Location>() { new Location{ City = "one" }, new 
Location{ City = "two" } };

List<User> user= new List<User>() { new User{ FirstName = "A", location = 
loc }, new User{ FirstName = "B" } };

return View(user);

-- View Section

@model IEnumerable<YourSolutionName.Models.User>

@foreach (var item in Model)
        @Html.DisplayFor(modelItem => item.FirstName)

          if (item.location != null) {  
        foreach(var i in item.location)

This is one approach by using, we can use two different models on same view.

As for demo i added static values you can add dynamic using your context object. it may help you. Thank You

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow