删除多对多关系中的记录

时间:2015-06-10 11:34:52

标签: c# many-to-many

当我删除电影时,我收到有关外国外键的错误。我的问题是如何删除表格MovieActor中我要删除的ID电影的所有记录?还有电影桌上的电影?我不可能编写代码,当我删除电影时会自动执行此操作吗?

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"));
    }

2 个答案:

答案 0 :(得分:1)

试试这个

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();
}

答案 1 :(得分:0)

据我所知,这是一个问题,当你建立多对多的关系时,因为你不能删除任何东西,因为两者都是相互引用的。

解决方案是制作另一张桌子(在你的情况下让我们说是角色),这将是与演员和电影的一对多关系。查看many-to-many relationship in database design了解详情。