1

i have an entitity:

public virtual int RecommendedUserId { get; set; }
public virtual string Firstname { get; set; }
public virtual string Surname { get; set; }
public virtual string Email { get; set; }
public virtual string JobTitle { get; set; }
public virtual DateTime? DateAndTimeProcessed { get; set; }
public virtual DateTime? DateAndTimeRecommended { get; set; }
public virtual string ReasonForRejection { get; set; }

//  User also an entity and has property UserId
public virtual User RecommendedByUser { get; set; }
public virtual User AssignedToUser { get; set; }

in my controller i have:

   Entities.RecommendedUser user = new RecommendedUser();
   user.Firstname = model.Firstname;
   user.Surname = model.Surname;
   user.Email = model.Email;
   user.JobTitle = model.JobTitle;

   // why am i getting the Object reference not set to 
   // an instance of an object error??
   user.RecommendedByUser.UserId = CurrentUser.UserId;  

if I instantiate RecommendedUser dont i instantiate User within RecommendedUser as well??

Kjartan
  • 18,591
  • 15
  • 71
  • 96
charlie_cat
  • 1,830
  • 7
  • 44
  • 73
  • No, each object must be instantiated. Or, the default constructor of RecommendedUser() must create a new RecommendedByUser() somehow. – mtsiakiris Apr 26 '13 at 08:37

4 Answers4

3

You are not instantiating the RecommendedByUser of user; you are only instatiating the user.

   user.Firstname = model.Firstname;
   user.Surname = model.Surname;
   user.Email = model.Email;
   user.JobTitle = model.JobTitle;
   user.RecommendedByUser = new RecommendedUser(); // or whatever the exact type is, maybe just User
   user.RecommendedByUser.UserId = CurrentUser.UserId; 
daryal
  • 14,643
  • 4
  • 38
  • 54
2

Value types are initialized with the class. However child objects can be NULL as they are reference types. Those objects need to be initialized before they can be assigned to a property.

I assume you are using a technology like Entity Framework. Frameworks like this allow you to prefetch these objects so they will be fetched (and initialized) when you get the entity from your datasource. However when creating new objects you will need to create them yourself.

Myrtle
  • 5,761
  • 33
  • 47
0

In the case of EntityFramework, there is the Lazy loading feature. In your specific case that does not apply because your object is not tracked by the EF context. Lazy loading (and then automatic instanciation) is only active if your object is tracked.

This thread could be instructive.

Community
  • 1
  • 1
Askolein
  • 3,250
  • 3
  • 28
  • 40
0

You should always first check for null values Like:

if(user.Firstname != null)
{
  user.Firstname = model.Firstname;
}

To avoid nullpointer exceptions

Paul.K
  • 3
  • 1
  • 3
  • In your example, it is useless. More like: `if(user != null && model != null) user.FirstName = model.FirstName;` – Askolein Apr 26 '13 at 09:58