Delete One-to-Many Entities using ObjectContext:

Connected Scenario:

In this article, we will see how to delete One-to-Many entities using ObjectContext.

 

Following code deletes the teacher for standard which has One-to-Many relationship from the database in connected scenario:

                        
        using (var ctx = new SchoolDBContext())
        {
            //fetching existing standard from the db
            Standard std = (from s in ctx.Standards
                            where s.StandardName == "standard3"
                            select s).FirstOrDefault<Standard>();

            //getting first teacher to be removed
            Teacher tchr = std.Teachers.FirstOrDefault<Teacher>();
            //removing teachers 
            if (tchr != null)
                ctx.Teachers.DeleteObject(tchr);

            //Do not use std.Teachers.Remove(tchr). It will give exception. 
            //This statement doesn't remove teacher from teachers collection but it trying to 
            //remove relationship.
            //std.Teachers.Remove(tchr);

            ctx.SaveChanges();
        }

As you can see in above code, we remove the teacher by ctx.Teachers.DeleteObjct(teacher). This will delete the teacher from the database table. Do not use std.Teacher.Remove(teacher) because this statement will try to delete the standard and teacher relationship. So be careful while deleting.

 

Disconnected Scenario:

Following code deletes the teacher for standard (which has One-to-Many relationship) from the database in disconnected scenario:

                        
        Standard std = null;

        using (var ctx = new SchoolDBContext())
        {
            ctx.ContextOptions.LazyLoadingEnabled = false;

            //fetching existing standard from the db
            std = (from s in ctx.Standards.Include("Teachers")
                   where s.StandardName == "standard3"
                            select s).FirstOrDefault<Standard>();
        }
        //Creating new context
        using (var newCtx = new SchoolDBContext())
        {
            //getting first teacher to be removed
            Teacher tchr = std.Teachers.FirstOrDefault<Teacher>();

            newCtx.Teachers.Attach(tchr);
            //removing teachers 
            newCtx.Teachers.DeleteObject(tchr);

            //Do not use std.Teachers.Remove(tchr). It will give exception. 
            //This statement doesn't remove teacher from teachers collection 
            //but it trying to remove relationship.
            //std.Teachers.Remove(tchr);

            newCtx.SaveChanges();
        }

As you can see in above code, we first attach the teacher entity in Teachers entityset in new context object. Then we delete it from the collection. Thus you can delete the One-to-Many entity graph in disconnected scenario.

 

 

 

 

Entity Framework