Can't set additional foreign key to null with independent association

I have an optional independent foreign key of an association in my application, here is a simplified version in context and entity db.

Context

public class AppContext : DbContext
{
    public DbSet<Foo> Foos { get; set; }
    public DbSet<Bar> Bars { get; set; }
    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Bar>().HasOptional(b => b.Foo);
    }
}

      

Objects

public class Foo
{
    public int Id { get; set; }
    public virtual ICollection<Bar> Bars { get; set; }
}
public class Bar
{
    public int Id { get; set; }
    public virtual Foo Foo { get; set; }
}

      

The context and entities are located in a different assembly and I cannot change the entities as this is a subrepository and will be used by other projects.

Problem

When I want to remove the foreign key by setting it to null, it doesn't change.

using (var db = new AppContext())
{
    var bar = db.Bars.Find(1);
    bar.Foo = null;
    db.SaveChanges();
}

      

It works

bar.Foo.Bars.Remove(bar);

      

but in my case this is not a solution, all the bars will be loaded into memory and I don't want to have an unnecessary round trip database.

Why and how can I solve this?

+3


source to share


1 answer


I managed to solve it by assigning it to an unused variable.

var bar = db.Bars.Find(1);
var foo = bar.Foo;
bar.Foo = null;
db.SaveChanges();

      



PS: Assigning zero two or more does not work.

bar.Foo = null;
bar.Foo = null;

      

+3


source







All Articles