Entity Framework : referencing other objects

37 views Asked by At

I have a Movie class that has lists of Actors and Directors. Whenever I'm creating a Movie (using a Rest API) that uses those, everything's fine.

But when I'm creating a second one with an already existing Actor / Director, my first Movie loses its reference to said Actor/Director.

How can I fix this so that it doesn't do that? Should I create a new class that references Movies and Actors/Directors? How should I do that?

Here's my class in case anything catches the eye.

public class Movie
{
    public int Id { get; set; }
    public required string Title { get; set; }
    public required List<Actor> Actors { get; set; }
    public required List<Director> Directors { get; set; }
}

I'm using Entity Framework's InMemory database system.

Everything else seems to be working correctly. The Movie references Actors and Directors, but not the other way around, I would like to avoid that.

1

There are 1 answers

1
Moho On BEST ANSWER

You should really provide the models for Actor and Director as well but, based on the behavior, I assume you set up 1:N relationships from Actor|Director to Movie, so each Actor and Director can only associate with a single Movie. The relationship should be set up as many-to-many as a film can have multiple actors/directors and actors/directors can have multiple films, so Actor|Director should also have a List<Movie> Movies property instead of Movie Movie properties and/or the fluent config should be set up appropriately:

builder.Entity<Movie>
    .HasMany( m => m.Actors )
    .WithMany( a => a.Movies );
    // or, if no corresponding navigation properties on Movies
    // .WithMany();

https://learn.microsoft.com/en-us/ef/core/modeling/relationships/many-to-many