user842876
user842876

Reputation: 55

Entity Framework Code First Many to Many NullReference

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; }
}

Upvotes: 2

Views: 793

Answers (2)

Kevin Aleshire
Kevin Aleshire

Reputation: 11

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();
}

Upvotes: 1

Matt Hamilton
Matt Hamilton

Reputation: 204219

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; } 
} 

Upvotes: 6

Related Questions