0

I have the following Model.

 public class Person
{
    public Guid ID { get; set; }

    [Required]
    [DataType(DataType.Text)]
    [Display(Name = "Prénom")]
    public string FirstName { get; set; }

    [Required]
    [DataType(DataType.Text)]
    [Display(Name = "Nom")]
    public string LastName { get; set; }

    [Required]
    [DataType("Users")]
    [Display(Name = "Adresse")]
    public Address Address { get; set; }

As you can see, it contains a public Field of Address Type:

    public class Address
{
    public Guid ID { get; set; }

    [Required]
    [DataType(DataType.Text)]
    [Display(Name = "Rue")]
    public string Street { get; set; }

    [Required]
    [DataType(DataType.Text)]
    [Display(Name = "Ville")]
    public string City { get; set; }

    [Required]
    [DataType(DataType.Text)]
    [Display(Name = "Province")]
    public string Province { get; set; }

I have no problem creating a new instance. Both the person and the address are posted into the database

 [HttpPost]
    public ActionResult Create(Person model)
    {
        if (ModelState.IsValid)
        {
            db.Persons.Add(model);
            db.SaveChanges();

I would like to understand why when I retrieve the Person from the db using the following commands, the Address is always NULL.

 return db.Persons.FirstOrDefault();

Thanks

0

1 Answer 1

4

You need to eager load the address property.

return db.Persons.Include("Address").FirstOrDefault();

If you need lazy loading behavior you need to mark Address property as virtual

[Required]
[DataType("Users")]
[Display(Name = "Adresse")]
public virtual Address Address { get; set; }
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot Eranga, I will try this out today.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.