删除多对多关系中的记录

Deleting records in many to many relation

当我删除电影时,出现关于外键的错误。我的问题是如何从我想删除的带有 ID 电影的 table MovieActor 中删除所有记录?在电影 table 的最后电影?不可能编写在我移除胶卷时自动执行此操作的代码?

Actors.cs

[Table("Actor")]
    public partial class Actor
    {
        public Actor()
        {
            Movie = new HashSet<Movie>();
        }

        public int ID { get; set; }

        [Required]
        [StringLength(50)]
        public string FirstName { get; set; }

        [Required]
        [StringLength(50)]
        public string LastName { get; set; }

        public virtual ICollection<Movie> Movie { get; set; }
    }

Movie.cs

[Table("Movie")]
    public partial class Movie
    {
        public Movie()
        {
            Actors = new HashSet<Actor>();
            Countries = new HashSet<Country>();
            Directors = new HashSet<Director>();
            Genres = new HashSet<Genre>();
            Writers = new HashSet<Writer>();
        }

        public int ID { get; set; }

        [Required]
        [StringLength(50)]
        public string Title { get; set; }

        [StringLength(50)]
        public string Title2 { get; set; }

        public int Year { get; set; }

        [StringLength(255)]
        public string Description { get; set; }

        public int Lenght { get; set; }

        public string Poster { get; set; }

        public DateTime? DateAdded { get; set; }

        public long? BoxOffice { get; set; }

        public string TrailerLink { get; set; }

        public virtual ICollection<Actor> Actors { get; set; }

    }

Context.cs

 public partial class Context : DbContext
    {

         public Context()
            : base("name=DbModel")
        {
        }


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


        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Entity<Actor>()
                .HasMany(e => e.Movie)
                .WithMany(e => e.Actors)
                .Map(m => m.ToTable("MovieActor").MapLeftKey("ActorID").MapRightKey("MovieID"));
    }

试试这个

using(var context = new Context())
{   
    var movie = context.Movies.Single(x=>x.ID == movieID);

    var actors = context.Actors.Where(x=>x.Movie.Any(y=>y.ID == movie.ID));

    foreach(var actor in actors)
    {
        actor.Movies.Remove(movie);
    }

    context.SaveChanges();
}

据我所知,这是建立多对多关系时出现的问题,因为您无法删除任何内容,因为两者相互引用。

一个解决方案是制作另一个 table(假设您的情况是角色),这将是与 Actor 和 Movie 的一对多关系。检查 many-to-many relationship in database design 了解更多详情。