2

I keep getting a NullReferenceException on the su.Companies.Add(co); line. I would think that with the way my models are defined it should work. Autocomplete, to sound like a newbie, completes this just fine. I'm obviously new to EntityFramework.

Help?

using (var db = new TicketdocketEntities())
{
  var su = new SiteUser { UserName = model.UserName };
  db.SiteUser.Add(su);
  var co = new Company { Name = "Hello" };
  su.Companies.Add(co);
  db.SaveChanges();
}

Models

public class Company
{
  [Key]
  public int CompanyId { get; set; }
  public string Name { get; set; }

  public virtual ICollection<SiteUser> SiteUsers { get; set; }
}

public class SiteUser
{
  [Key]
  public int SiteUserID { get; set; }
  public string UserName { get; set; }

  public virtual ICollection<Company> Companies { get; set; }
}

public class TicketdocketEntities : DbContext
{
    public DbSet<Company> Companies { get; set; }
    public DbSet<SiteUser> SiteUser { get; set; }
}

2 Answers 2

6

You still need to initialize the property with an actual list:

public class SiteUser 
{ 
    public SiteUser()
    {
        Companies = new List<Company>();
    }

    [Key] 
    public int SiteUserID { get; set; } 
    public string UserName { get; set; } 

    public virtual ICollection<Company> Companies { get; set; } 
} 
Sign up to request clarification or add additional context in comments.

3 Comments

Problem is, that it should work without this workaround because modifier virtual should mean, that collection will be lazy loaded. When you create construction like this, everytime when you select SiteUser the EF will instantiate new SiteUser and fill it with data from database but list of Companies will be empty, because of constructor called
And to add, from some unspecified reason the collection is not lazy loaded
thank you! i have been looking around and couldnt find an answer but this worked!
1

For others who may run into this problem (as I just did) ....

Initializing the property with an actual list is the correct way to fix the NullReferenceException. However, as marek_lani pointed out, it should not be done within the model itself as all SiteUser objects will have an empty list of Companies and then need to be populated. The proper way, or what worked better for me, was to place the same code within the controller action prior to the su.Companies.Add() statement.

using (var db = new TicketdocketEntities())
{
    var su = new SiteUser 
        { 
            UserName = model.UserName,
            Companies = new List<Company>()
        };
    db.SiteUser.Add(su);
    var co = new Company { Name = "Hello" };
    su.Companies.Add(co);
    db.SaveChanges();
}

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.