Entity Framework Core: Include many-to-many related objects in WebAPI

asp.net-core asp.net-core-webapi entity-framework entity-framework-core linq

Question

I'm not too familiar with the .NET framework but decided to try out ASP.NET Core and EF Core. I want to make a pretty simple Web API backend but I'm having trouble working with many-to-many relationships.

I understand that I need to make a relationship table for the two entities, as in the example from this post: How to create a many to many relationship with latest nightly builds of EF Core?

I also have my model builder creating the relationship as described here http://ef.readthedocs.io/en/latest/modeling/relationships.html#many-to-many

My code looks like this:

in DBContext:

protected override void OnModelCreating(ModelBuilder builder)
    {
        base.OnModelCreating(builder);

        builder.Entity<MovieActor>().HasKey(x => new { x.MovieId, x.ActorId});

        builder.Entity<MovieActor>()
            .HasOne(m => m.Movie)
            .WithMany(ma => ma.MovieActors)
            .HasForeignKey(m => m.MovieId);

        builder.Entity<MovieActor>()
            .HasOne(m => m.Actor)
            .WithMany(ma => ma.MovieActors)
            .HasForeignKey(a => a.ActorId);

    }

    public DbSet<Movie> Movies { get; set; }

    public DbSet<Actor> Actors { get; set; }


}

Models:

namespace Test.Models
{
    public class Movie
    {
        public int MovieId { get; set; }
        public string Title { get; set; }
        public DateTime ReleaseDate { get; set; }
        public string Code { get; set; }
        public string Path { get; set; }

        public ICollection<MovieActor> MovieActors { get; set; }
    }

    public class Actor
    {
        public int ActorId { get; set; }
        public string Name { get; set; }
        public ICollection<MovieActor> MovieActors { get; set; }
    }

    public class MovieActor
    {
        public int MovieId { get; set; }
        public Movie Movie { get; set; }

        public int ActorId { get; set; }
        public Actor Actor { get; set; }
    }
}

This seems to be working for the most part. I can create new MovieActor objects and add them to the database. One thing that seems odd is the Movie and Actor models now have a MovieActors property but it's always null, despite the join table having entries.

The thing I can't figure out is how to retrieve these related objects in my WebAPI controllers. My Linq skills are very weak, so maybe I just need to brush up on that, but I don't know where to start. When I get a movie by ID, or get a list of all movies, I'd like the result to have any related Actors in an array on the object. The same goes in the other direction, when getting an Actor I want to get an array of their movies.

Here is one of my controller methods trying to make use of this relationship:

        // POST: api/Movie
    [HttpPost]
    public IActionResult PostMovie([FromBody] MovieBundle Moviebundle)
    {


        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }

        var _movie = _context.Movies.FirstOrDefault(m => m.Code == Moviebundle.Movie.Code);
        if(_movie == null)
        {
            //Doesn't exist! add a new one
            _movie = Moviebundle.Movie;
            _context.Movies.Add(_movie);
            _context.SaveChanges();

            foreach (Actor actor in Moviebundle.actors)
            {
                //Try to look up by name
                Actor _actor = _context.Actors.FirstOrDefault(a => a.Name == actor.Name);

                //If they don't exist, add them to the DB 
                if (_actor == null)
                {
                    _context.Actors.Add(actor);
                    _context.SaveChanges();
                    _actor = actor;
                }

                //This is what I'm using to create the M-t-M relationship
                var link = new MovieActor { Actor = _actor, Movie = _movie };
                _context.MovieActor.Add(link); //This line gives an error


            }


        } else
        {
            return new StatusCodeResult(StatusCodes.Status409Conflict);
        }




        try
        {
            _context.SaveChanges();
        }
        catch (DbUpdateException)
        {
            if (MovieExists(_movie.MovieID))
            {
                return new StatusCodeResult(StatusCodes.Status409Conflict);
            }
            else
            {
                throw;
            }
        }

        return CreatedAtAction("GetMovie", new { id = _movie.MovieID }, _movie);
    }
1
3
5/23/2017 12:34:44 PM

Popular Answer

You have to change it as shown below.

Models :

namespace Test.Models
{
    public class Movie
    {
        public int MovieId { get; set; }
        public string Title { get; set; }
        public DateTime ReleaseDate { get; set; }
        public string Code { get; set; }
        public string Path { get; set; }

        public ICollection<MovieActor> MovieActors { get; set; }
    }

    public class Actor
    {
        public int ActorId { get; set; }
        public string Name { get; set; }
        public ICollection<MovieActor> MovieActors { get; set; }
    }

    public class MovieActor
    {
        public int MovieId { get; set; }
        public Movie Movie { get; set; }

        public int ActorId { get; set; }
        public Actor Actor { get; set; }
    }
}

Context :

protected override void OnModelCreating(ModelBuilder builder)
    {
        base.OnModelCreating(builder);

        builder.Entity<MovieActor>().HasKey(x => new { x.MovieId, x.ActorId});

        builder.Entity<MovieActor>()
            .HasOne(m => m.Movie)
            .WithMany(ma => ma.MovieActors)
            .HasForeignKey(m => m.MovieId);

        builder.Entity<MovieActor>()
            .HasOne(m => m.Actor)
            .WithMany(ma => ma.MovieActors)
            .HasForeignKey(a => a.ActorId);

    }

    public DbSet<Movie> Movies { get; set; }

    public DbSet<Actor> Actors { get; set; }

    public DbSet<MovieActor> MovieActors { get; set; }

 }

You can navigate as shown below :

var actor = context.Actors
                   .Include(r => r.MovieActors)
                   .FirstOrDefault(a=>a.ActorId = 1)

var movies = actor.MovieActors.Select(c => c.Movie);

How to add a record :

var actor = new Actor { ... };
context.Actors.Add(actor);

var movie = new Movie { ... };
context.Movies.Add(movie);

var movieActor = new MovieActor { Actor = actor , Movie = movie };
context.MovieActors.Add(movieActor);

context.SaveChanges();
5
9/24/2016 7:52:45 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow