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

前端 未结 1 1286
天命终不由人
天命终不由人 2021-01-06 19:21

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

1条回答
  •  执笔经年
    2021-01-06 19:40

    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 MovieActors { get; set; }
        }
    
        public class Actor
        {
            public int ActorId { get; set; }
            public string Name { get; set; }
            public ICollection 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().HasKey(x => new { x.MovieId, x.ActorId});
    
            builder.Entity()
                .HasOne(m => m.Movie)
                .WithMany(ma => ma.MovieActors)
                .HasForeignKey(m => m.MovieId);
    
            builder.Entity()
                .HasOne(m => m.Actor)
                .WithMany(ma => ma.MovieActors)
                .HasForeignKey(a => a.ActorId);
    
        }
    
        public DbSet Movies { get; set; }
    
        public DbSet Actors { get; set; }
    
        public DbSet 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();
    

    0 讨论(0)
提交回复
热议问题