Géza
Géza

Reputation: 2762

Entity Framework - Code First using custom constructors for many to many relationships

As far as I did research on defining many to many relations with Code First, I guess that custom constructors in the entity classes are only needed for the purpose of being able to create a new instance of an entity plus the n:m-related entity AT ONCE.

At the moment I have my classes defined like this:

public class Person
{
    public Person()
    {
        Events = new HashSet<Event>();
    }

    public int PersonId { get; set; }
    public virtual ICollection<Event> Events { get; set; }
}

public class Event
{
    public Event()
    {
        Persons = new HashSet<Person>();
    }

    public int EventId { get; set; }
    public virtual ICollection<Person> Persons { get; set; }
}

However, if my application will never offer the possibility to create a new Person during creating a new Event, can I simply omit the custom constructor for Events?

public class Event
{   
    public int EventId { get; set; }
    public virtual ICollection<Person> Persons { get; set; }
}

Will the many to many relation still work fine?

Upvotes: 0

Views: 1651

Answers (1)

Cosmin Onea
Cosmin Onea

Reputation: 2738

If you do that you'll get a NullReferenceException when you create a new event and try to add Persons to it.

var @event = new Event();
event.Persons.Add(new Person()); //NullReferenceException here

that is the only reason for that constructor, to initialise the collections.

you can initialise the Persons collection lazily inside the getter on first access but you need to be careful with multithreading.

Upvotes: 1

Related Questions