1

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?

1
  • dtryon is correct. You are missing virtual keyword. Commented Feb 10, 2012 at 14:43

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

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.