ASP.NET Core trouble in model binding

asp.net-core c# entity-framework-core

Question

I'm new in ASp.NET Core. All data saved in database correctly, i tried show model data in View. Person model data gotten correctly, but second model Address didn't show in View. I suspect I made a mistake in the controller.

First model:

public class Person
    {
        public int PersonID { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public Address HomeAddress { get; set; }
    }

Second model:

public class Address
    {
        public int ID { get; set; }
        public string Line { get; set; }
        public string City { get; set; }
        public string PostalCode { get; set; }
        public string Country { get; set; }

        public int PersonId { get; set; }
        public Person Person { get; set; }
    }

Controller code:

public IActionResult Index()
        {

            return View(_repository.Persons);
        }
        [HttpGet]
        public ViewResult Create()
        {
            return View();
        }
        [HttpPost]
        public IActionResult Create(PersonCreateViewModel p)
        {
            var obj = new Person
            {
                FirstName = p.FirstName,
                LastName = p.LastName,
                BirthDate = p.BirthDate,
                HomeAddress = p.HomeAddress,
                Role = p.Role,
                IsApproved = p.IsApproved
            };
            _repository.Add(obj);
            return View();
        }

View:

@model IEnumerable<Person>
@{
    ViewData["Title"] = "Home Page";
}
<div class="text-center">
    @foreach(var p in Model)
    {
        <p>Name - @p.FirstName</p>
        <p>Last Name - @p.LastName</p>
        <p>Role - @p.Role</p>
        <p>Line - @p.HomeAddress?.Line</p>
        <p>City - @p.HomeAddress?.City</p>
    }
    <hr />
</div>
1
1
4/1/2020 11:47:18 AM

Accepted Answer

As the user Mustapha Larhrouch said in his comment, one way to fix this is to use the include method on your property to load related data, so _repository.Persons.Include(p => p.Adress)

There are several ways Entity Framework Core loads related data from Database like Eager loading, Explicit loading and Lazy loading, the method above is called Eager loading

I suggest you take a look at Loading Related Data from MS docs. Or the lazy loading section in Querying in Entity Framework Core

2
4/1/2020 8:17:57 AM


Related Questions





Related

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