简体   繁体   English

在Entity Framework Core中使用具有多对多关系的列表

[英]Using Lists with Many-to-Many relationship in Entity Framework Core

So i'm developing a basic project which uses Entity Framework Core to create a database that fetches information from TMDB based on whatever movie I enter to try and understand the whole thing better. 因此,我正在开发一个基础项目,该项目使用Entity Framework Core创建一个数据库,该数据库根据我输入的任何影片从TMDB获取信息,以更好地理解整个事物。

I've been stuck for a while trying to implement a Many-to-Many relationship between my Movie and Studio models. 在尝试在Movie和Studio模型之间实现多对多关系时,我已经停留了一段时间。

Movies can have many studios attributed to them, but there are also many movies that will be connected to the studios, so it's the clear relationship to use. 电影可以归因于许多电影制片厂,但也有许多电影将与电影制片厂建立联系,因此使用之间存在明显的关系。 Below are snippets from those models: 以下是这些模型的摘要:

public class Movies
{
    [Key]
    public int MovieID { get; set; }
    public ICollection<MovieStudios> MovieStudios { get; set; } = new List<MovieStudios>();
}
public class Studios
{
    [Key]
    public int StudioID { get; set; }
    public ICollection<MovieStudios> MovieStudios { get; set; } = new List<MovieStudios>();
}

And here is the join table that i've got 这是我得到的联接表

public class MovieStudios
{
    public int MovieID { get; set; }
    public Movies Movie { get; set; }
    public int StudioID { get; set; }
    public Studios Studio { get; set; }
}

And here is my DbContext class: public class MyDbContext : DbContext { public DbSet TblMovies { get; 这是我的DbContext类:public class MyDbContext:DbContext {public DbSet TblMovies {get; set; 组; } public DbSet TblStudios { get; }公用DbSet TblStudios {get; set; 组; } }

    protected override void OnConfiguring(DbContextOptionsBuilder option)
    {
        option.UseSqlServer(@"Server=(localdb)\MSSQLLocalDB; Database=ServerDatabase ; Trusted_Connection=True;");
    }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<MovieStudios>()
            .HasKey(bc => new { bc.MovieID, bc.StudioID });
    }
}

What I want to do, in one of my services, is return List so that I can link these studios to the movie in question when a movie is added to the database, but i'm just completely lost as for what to do. 在我的一项服务中,我想做的就是返回列表,以便在将电影添加到数据库时可以将这些工作室链接到有问题的电影,但是我完全不知道该怎么做。 Sorry if this is a noob question, of if this is too long, just feel completely lost! 抱歉,如果这是一个菜鸟问题,或者如果时间太长,请完全迷失!

EDIT: To be more specific, I pass through the TMDB id of a film to a service i've created that returns a list of the ids of the films production studios eg('46226', '6735'), which is then saved in my database and also returns the index number of my Studio database so that it can be added to my film. 编辑:更具体地说,我将电影的TMDB ID传递给我创建的服务,该服务返回电影制作工作室ID的列表,例如('46226','6735'),然后将其保存在我的数据库中,并且还返回Studio数据库的索引号,以便可以将其添加到我的电影中。 ('1', '4', '6'). (“ 1”,“ 4”,“ 6”)。 I've stored this as a List and am stuck as to how I can add these studio ids to the film i'm trying to add to the database. 我已将其存储为列表,并且对如何将这些工作室ID添加到要添加到数据库中的电影感到困惑。 All examples i've seen don't really address what i'm trying to do. 我所见过的所有示例并没有真正解决我正在尝试做的事情。 I'm trying to add Many studios to the one film. 我正在尝试将许多工作室添加到一部电影中。

The correct way to do it is this one: 正确的方法是:

// define composite key for MovieStudios
modelBuilder
    .Entity<MovieStudios>()
    .HasKey(ct => new {ct.MovieId, ct.StudioId});

// setup one-to-many relationship MovieStudios-Movies
modelBuilder.Entity<MovieStudios>()
    .HasOne(movieStudio => movieStudio.Movie)
    .WithMany(movie => movie.MovieStudios)
    .HasForeignKey(movieStudio => movieStudio.MovieId);

// setup one-to-many relationship MovieStudios-Studios
modelBuilder.Entity<MovieStudios>()
    .HasOne(movieStudio => movieStudio.Studio)
    .WithMany(studio => studio.MovieStudios)
    .HasForeignKey(movieStudio => movieStudio.StudioId);

A many-to-many relationship between Movies and Studios is equivalent to two one-to-many relationships between MovieStudios (relationship table) and Movies and Studios respectively. MoviesStudios之间many-to-many关系分别相当于MovieStudios (关系表)与MoviesStudios之间的两个one-to-many关系。

Edit: 编辑:

You can add movies to a studio like this: 您可以像这样将电影添加到工作室:

public async Task AddMoviesToStudioAsync(List<Movie> movies, int studioId) 
{
    var movieStudiosList
        = movies.Select(
            movie => new MovieStudios
            {
                MovieId = movie.Id, 
                StudioId = studioId
            })
            .ToList();

    await DbContext.Set<MovieStudios>().AddRangeAsync(movieStudiosList);
}

If you want to add Many studios to the one film, you could try to use a for looping. 如果要在一部电影中添加许多工作室,则可以尝试使用for循环播放。

Try to the code shown below in your action 尝试执行下面显示的代码

public async Task<IActionResult> AddStudiosToMovie(int  movieID, List<int> studioIdList)
    {
       for(int i=0;i<studioIdList.Count();i++)
        {
            var movieToStudio = new MovieStudios
            {
                MovieID = movieID,
                StudioID = studioIdList[i]
            };
            _context.Add(movieToStudio);
            await _context.SaveChangesAsync();
        }

        return RedirectToAction(nameof(Index));

    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM