Reputation: 2755
I am attempting to build an ASP.NET MVC 4 web app, which is similar to a very basic e-mail system, using Entity Framework's code first approach. To demonstrate the problem I am having, consider the following C# classes.
public class Message
{
public int Id { get; set; }
[Required]
public User From { get; set; }
[Required]
public User To { get; set; }
[Required]
public string Subject { get; set; }
[Required]
public string Content { get; set; }
[Required]
[DataType(DataType.DateTime)]
public DateTime CreatedAt { get; set; }
public bool IsRead { get; set; }
public bool IsTrash { get; set; }
public bool IsSpam { get; set; }
}
public class User
{
public int Id { get; set; }
public string Name { get; set; }
public string Password { get; set; }
public ICollection<Role> Roles { get; set; }
public string Email { get; set; }
}
After seeding the database, the first message column appears like so:
Id Subject Content CreatedAt IsRead IsTrash IsSpam From_Id To_Id
1 Howdy Lorem 2012-02-10 0 0 0 2 1
And two users, with the IDs listed above, exist in the Users table.
If I run the following LINQ, it shows that both From and To for that message are null but all other fields are correctly populated:
dbContext.Messages.Single(o=>o.Id==1);
What am I doing wrong that would lead to those two fields being null? Is it possibly a flaw in the organization of my classes?
Upvotes: 1
Views: 843
Reputation: 9296
The thing is that From and To belong to are complex type and you should declare them as virtual
so that they can be loaded correctly.
Upvotes: 2