none
mvc 5 ef6 Delete Many- to Many RRS feed

  • Question

  • I am trying to delete an item using MVC 5 and EF 6. For some reason EF has map my object as shown below

    .Map(m => m.ToTable("DocStaging").MapLeftKey("AuthorsId").MapRightKey("DocumentId"));
    


    I am using the code below to do Delete but is not working

    var cont = (from c in  _docRepositoryAsync.Queryable()
    .Include(x => x.Headers)
    where c.ContractId == contId
    select c).FirstOrDefault<Contract>();

    I am getting the error below

    The operation failed: The relationship could not be changed because one or more of the foreign-key properties is non-nullable. When a change is made to a relationship, the related foreign-key property is set to a null value. If the foreign-key does not support null values, a new relationship must be defined, the foreign-key property must be assigned another non-null value, or the unrelated object must be deleted.


    Ebenezer

    Tuesday, July 5, 2016 1:48 AM

Answers

  • Hi denkyira,

    According to your description and code snippet,  Since your code is not complete, I couldn't reproduce your issue on my side.

    Based on your requirement (delete many - to - many), I create a simple as below for your reference.

    #Models.

    using System.Collections.Generic;
    using System.ComponentModel.DataAnnotations;
    
    namespace ManyToManyFullDemo
    {
        public class Student
        {
            public Student() { }
    
            public int StudentId { get; set; }
            [Required]
            public string StudentName { get; set; }
    
            public int StdandardId { get; set; }
    
            public virtual ICollection<Course> Courses { get; set; }
        }
    
        public class Course
        {
            public Course()
            {
                this.Students = new HashSet<Student>();
            }
    
            public int CourseId { get; set; }
            public string CourseName { get; set; }
    
            public virtual ICollection<Student> Students { get; set; }
        }
    
    }
    

    #DbContext

    namespace ManyToManyFullDemo
    {
        using System.Data.Entity;
    
        public partial class EFDemoContext : DbContext
        {
            public EFDemoContext()
                : base("name=EFDemoContext")
            {
            }
    
            public DbSet<Student> Students { get; set; }
            public DbSet<Course> Courses { get; set; }
            protected override void OnModelCreating(DbModelBuilder modelBuilder)
            {
                modelBuilder.Entity<Student>()
                    .HasMany<Course>(s => s.Courses)
                    .WithMany(c => c.Students)
                    .Map(cs =>
                    {
                        cs.MapLeftKey("StudentRefId");
                        cs.MapRightKey("CourseRefId");
                        cs.ToTable("StudentCourse");
                    });
    
    
            }
        }
    }
    

    #Usage:
    using (var dbCtx = new EFDemoContext())
                {
                    //delete 
    
                    var student = dbCtx.Students.Include("Courses").Where(s => s.StudentId.Equals(1)).FirstOrDefault();
    
                    dbCtx.Students.Remove(student);
    
                    dbCtx.SaveChanges();
                }
    

    For more information about Delete Many-to-Many Entities, please refer to:

    http://www.entityframeworktutorial.net/delete-many-to-many-entities-in-entity-framework.aspx

    Best regards,

    Cole Wu


    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click HERE to participate the survey.

    • Marked as answer by denkyira Tuesday, July 5, 2016 2:42 PM
    Tuesday, July 5, 2016 8:46 AM
    Moderator

All replies

  • Hi denkyira,

    According to your description and code snippet,  Since your code is not complete, I couldn't reproduce your issue on my side.

    Based on your requirement (delete many - to - many), I create a simple as below for your reference.

    #Models.

    using System.Collections.Generic;
    using System.ComponentModel.DataAnnotations;
    
    namespace ManyToManyFullDemo
    {
        public class Student
        {
            public Student() { }
    
            public int StudentId { get; set; }
            [Required]
            public string StudentName { get; set; }
    
            public int StdandardId { get; set; }
    
            public virtual ICollection<Course> Courses { get; set; }
        }
    
        public class Course
        {
            public Course()
            {
                this.Students = new HashSet<Student>();
            }
    
            public int CourseId { get; set; }
            public string CourseName { get; set; }
    
            public virtual ICollection<Student> Students { get; set; }
        }
    
    }
    

    #DbContext

    namespace ManyToManyFullDemo
    {
        using System.Data.Entity;
    
        public partial class EFDemoContext : DbContext
        {
            public EFDemoContext()
                : base("name=EFDemoContext")
            {
            }
    
            public DbSet<Student> Students { get; set; }
            public DbSet<Course> Courses { get; set; }
            protected override void OnModelCreating(DbModelBuilder modelBuilder)
            {
                modelBuilder.Entity<Student>()
                    .HasMany<Course>(s => s.Courses)
                    .WithMany(c => c.Students)
                    .Map(cs =>
                    {
                        cs.MapLeftKey("StudentRefId");
                        cs.MapRightKey("CourseRefId");
                        cs.ToTable("StudentCourse");
                    });
    
    
            }
        }
    }
    

    #Usage:
    using (var dbCtx = new EFDemoContext())
                {
                    //delete 
    
                    var student = dbCtx.Students.Include("Courses").Where(s => s.StudentId.Equals(1)).FirstOrDefault();
    
                    dbCtx.Students.Remove(student);
    
                    dbCtx.SaveChanges();
                }
    

    For more information about Delete Many-to-Many Entities, please refer to:

    http://www.entityframeworktutorial.net/delete-many-to-many-entities-in-entity-framework.aspx

    Best regards,

    Cole Wu


    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click HERE to participate the survey.

    • Marked as answer by denkyira Tuesday, July 5, 2016 2:42 PM
    Tuesday, July 5, 2016 8:46 AM
    Moderator
  • Hi Cole

    Thanks a lot. Let me Implement your solution now and give you feedback

    Eb


    Ebenezer

    Tuesday, July 5, 2016 10:07 AM
  • Hi Cole

    Thanks a lot. Your post helped me. Got it working

    Eb


    Ebenezer

    Tuesday, July 5, 2016 2:43 PM