I am new to Entity Framework. Just wondering what is the right way to create related entities with many-to-many relationships. I always get this error when debugging: "Object reference not set to an instance of an object".
Take the following as an example:
Below is the data model, a Club can have multiple Members, a Member can join multiple clubs
public class Club
{
public int Id { get; set; }
public string Name { get; set; }
public virtual ICollection<Member> Member { get; set; }
}
public class Member
{
public int Id { get; set; }
public string Name { get; set; }
public virtual ICollection<Club> Club { get; set; }
}
I tried to create a new Club and add a new Member to it (Neither object is existing data in the DB):
Member member = new Member();
Club club=new Club();
member.Name = "Amy";
club.Name="NBA Fans";
member.Club.Add(club); //Error: Object reference not set to an instance of an object
db.Member.Add(member);
db.SaveChanges();
Can anyone please provide the right way to do this?
Thanks a lot