Prevent EF from saving full object graph

Viewed 429

I have a model as below

public class Lesson
{

    public int Id { get; set; }
    public Section Div { get; set; }

}

public class Section
{

    public int Id { get; set; }

    public string Name { get; set; }
}

I also have DB Context as below

public class MyContext : DbContext
{

    public MyContext() : base("DefaultConnection")
    {
        this.Configuration.LazyLoadingEnabled = false;
        this.Configuration.ProxyCreationEnabled = false;
    }

    public DbSet<Lesson> Lessons { get; set; }
    public DbSet<Section> Sections { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);
    }

}

Then I use the following code to call the database

            using (MyContext c = new EFTest.MyContext())
            {

                Lesson d = new EFTest.Lesson();
                Section ed = new EFTest.Section() { Name = "a" };
                d.Div = ed;

                c.Entry(d.Div).State = EntityState.Detached;

                c.Lessons.Add(d);
                c.SaveChanges();
            }

I am expecting this code to save just the Lesson object, not to save the full graph of Lesson and Section, but what happens is that it saves the full graph. How do I prevent it from doing that?

1 Answers

When you add an entity to DbSet, entityframework will add all of its relative. You need to detach the entity you don't want to add, after adding parent entity to DbSet.

using (MyContext c = new EFTest.MyContext())
{

    Lesson d = new EFTest.Lesson();
    Section ed = new EFTest.Section() { Name = "a" };
    d.Div = ed;

    c.Lessons.Add(d);

    c.Entry(d.Div).State = EntityState.Detached;

    c.SaveChanges();
}

if you want to add section, related to the lesson , you need to use the same context, or create a new context and load the lesson.

you can use this code

using (MyContext c = new EFTest.MyContext())
{

    Lesson d = new EFTest.Lesson();
    Section ed = new EFTest.Section() { Name = "a" };
    d.Div = ed;

    c.Lessons.Add(d);

    c.Entry(d.Div).State = EntityState.Detached;

    c.SaveChanges();

    //you can use this code
        ed.Lesson = d;
    // or this code
        d.Div = ed;

    c.Sections.Add(ed);
    c.SaveChanges();
}
Related