3

我有一个模型如下

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

我也有如下的数据库上下文

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

}

然后我使用下面的代码调用数据库

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

我希望这段代码只保存课程对象,而不是保存课程和部分的完整图表,但会发生的是它保存了完整的图表。我如何防止它这样做?

4

1 回答 1

0

当您将实体添加到 时DbSet,entityframework 将添加其所有相关的。在将父实体添加到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();
}

如果要添加与课程相关的部分,则需要使用相同的上下文,或者创建一个新的上下文并加载课程。

你可以使用这个代码

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();
}
于 2017-09-25T10:16:30.130 回答