Entity framework 6 Concept clear regarding Remove, RemoveRange, EntityState.Deleted

c# entity-framework entity-framework-6

Question

In my projects, I utilise Entity Framework 6 and I often have questions about certain ideas that are used while using EF to remove instances.

I'm still unsure of which one applies to which situation. I basically give them all a go, and if one works, I move on to the next until the code is sound. But no wi must comprehend this idea for all time. Despite my investigation, I was unable to fully grasp the notion.

In EF, I have a domain class with several referenced entities. An illustration. My domain class, Course, has the many referring objects that are listed in the code below.

public class Course
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Description { get; set; }

        public int CompanyId { get; set; }
        public virtual Company Company { get; set; }

        public virtual PricingSchedule PricingSchedule { get; set; }
        public virtual ICollection<CustomerCourse> AssignedCustomers { get; set; }

        public virtual ICollection<License> Licenses { get; set; }
        public virtual ICollection<GroupLicense> GroupLicenses { get; set; }
        public virtual ICollection<GroupCourse> GroupCourses { get; set; }
        public virtual ICollection<Learner> Learners { get; set; }
}

I now have to remove the course and all of its referring items from the database. For instance, if a course is being destroyed, all of its characteristics, such as AssignedCustomers and Licenses, must also be erased.

But utilising Entity framework, I don't grasp anything at all.

We have many alternatives for removing an entity from the database, including.

Remove
RemoveRange
EntityState.Deleted

In addition to Remove, RemoveRange, and Entitystate sometimes work. removed works Why?

My programme deletes a Course.

var courses = _context.Courses
                                              .Include("AssignedCustomers")
                                              .Include("PricingSchedule")
                                              .Include("Licenses")
                                              .Include("GroupCourses")
                                              .Include("GroupLicenses")
                                              .Where(e => courseIds.Contains(e.Id)).ToList();
                        if (courses != null && courses.Count > 0)
                        {
                            courses.ForEach(currentCourse =>
                            {

                                _context.Entry(currentCourse.PricingSchedule).State = EntityState.Deleted;

Sometimes removing a range makes the code function.

_context.CustomerCourses.RemoveRange(currentCourse.AssignedCustomers);

Why does the code below fail for me in one case but succeed in another?

 //currentCourse.AssignedCustomers.ToList().ForEach(ac =>
                    //{
                    //    //currentCourse.AssignedCustomers.Remove(ac);
                    //    _context.Entry(ac).State = EntityState.Deleted;
                    //});

                    _context.Entry(currentCourse).State = EntityState.Deleted;
                });
            }
            _context.SaveChanges();

Can someone please clarify the differences between each circumstance and the appropriate usage?

The most frequent mistake I encounter is

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.

When I use this piece of code, this error appears.

 currentCourse.AssignedCustomers.ToList().ForEach(ac =>
                        {

                            _context.Entry(ac).State = EntityState.Deleted;
                        });

OR

 currentCourse.AssignedCustomers.ToList().ForEach(ac =>
                            {

                                currentCourse.AssignedCustomers.Remove(ac):
                            });

I then press SaveChanges, and an error appears.

1
0
8/28/2018 7:21:40 PM

Popular Answer

When deleting a course, Entity Framework needs to know which associated entities will be eliminated, thus you must set up the cascade rules in both your schema and Entity Framework. For instance, you could wish to cascade delete, while Learner probably has a key that can be nullified if a course is withdrawn.

If configured properly, you should only need to use:context.Courses.Remove(course); and the connected entities will be immediately deleted or disassociated. Start with a more basic example of your parent-child connections, where one kid is deleted in a cascade and another is separated from the parent using a nullable FK. Your present example seems to also feature many-to-many linkages (GroupCourses), thus the technique will change based on the mapping and relationships.

0
8/28/2018 10:11:09 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow