Search code examples
asp.net-mvcentity-framework-4entity-framework-4.1ef-code-firstentity-relationship

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

Solution

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