Reputation: 3141
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
Upvotes: 0
Views: 124
Reputation: 32447
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; }
Upvotes: 4