实体框架6关于Remove,RemoveRange,EntityState.Deleted的概念清晰 [英] Entity framework 6 Concept clear regarding Remove, RemoveRange, EntityState.Deleted

查看:317
本文介绍了实体框架6关于Remove,RemoveRange,EntityState.Deleted的概念清晰的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在项目中使用了Entity Framework 6,对于使用EF删除对象的某些概念,我始终有疑问.

I use Entity framework 6 in my projects and I always have doubts regarding some of the concepts which are used to delete objects using EF.

我仍然不知道哪种情况在哪种情况下有效.我只是尝试了所有方法,如果可以工作,我将其保留下来,直到代码起作用为止.但没有人需要一劳永逸地理解这个概念.我做了研究,无法清楚地理解这个概念.

I still don't know which one works in which scenario. I just try all and if one works I leave it until the code is working. But no wi need to understand this concept once and for all. I did my research my unable to understand the concept clearly.

我在EF中有一个域类,它具有多个引用实体.例如.我有一个名为 Course 的域类,它在代码中有下面提到的多个引用对象.

I have a domain class in EF which have multiple referencing entities. For example. I have a domain class called Course and It has multiple referencing objects mentioned below in the code.

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

现在,我必须从数据库中删除所有带有其引用实体的课程.例如,如果课程正在删除,则必须删除其所有属性,例如 AssignedCustomers 许可证等.

Now I have to delete the course from the DB with all of its referencing entities. For example, If the course is deleting then its properties like AssignedCustomers, Licenses etc all must be deleted.

但是我对使用实体框架一无所知.

But I don't understand one thing using Entity framework.

要从数据库中删除实体,我们有多种选择.

For deleting an entity from DB we have multiple options like.

Remove
RemoveRange
EntityState.Deleted

有时,Remove起作用,但有时,RemoveRange起作用,有时是Entitystate.Deleted起作用.为什么?

Sometimes Remove works but sometime RemoveRange Works and sometime Entitystate.Deleted works. Why?

我的代码用于删除课程

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;

有时删除范围有效并且代码成功运行

_context.CustomerCourses.RemoveRange(currentCourse.AssignedCustomers);

下面的代码行给我错误,但在其他情况下它为什么起作用?

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

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

谁能向我解释在哪种情况下我应该使用什么?

Can anyone explain to me the difference in which situation I should use what?

我大部分时间收到的错误是

The error I receive most of the time 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.

当我使用这段代码时出现此错误

This error comes up when I use this piece of code

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

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

OR

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

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

之后,当我点击SaveChanges时出现错误.

after that when I hit SaveChanges The error comes up.

推荐答案

您需要在架构和Entity Framework中设置级联规则,以便它知道在删除课程时将删除哪些相关实体.例如,您将要级联删除,而像Learner这样的其他人则可能具有可为空的键,如果课程被删除,则可以将其清除.

You need to set up the cascade rules in your schema and within Entity Framework so that it knows which related entities will be deleted when you go to delete a course. For instance you will want to cascade delete while others like Learner would likely have a null-able key which can be cleared if a course is removed.

提供正确的设置,您只需要使用:context.Courses.Remove(course);,相关实体将被自动删除或取消关联.从一个简单的父子关系示例开始,一个孩子要级联删除,另一个孩子要与可为空的FK关联.您当前的示例似乎还具有多对多关联(GroupCourses),因此,根据映射/关系,方法将有所不同.

Provided it is set up correctly, you should just need to use: context.Courses.Remove(course); and the related entities will be removed or disassociated automatically. Start with a simpler example of your parent-child relationships, one child to cascade delete, another to disassociate with a nullable FK. Your current example looks to also have many-to-many associations (GroupCourses) so depending on the mapping/relationships the approach will vary.

这篇关于实体框架6关于Remove,RemoveRange,EntityState.Deleted的概念清晰的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆