How do I keep Entity Framework from saving unmodified navigational properties

325 Views Asked by At

EDIT: It was solved by setting

aUpdate.b = null;
aUpdate.c = null;

before calling update. But this does not seem like the right way to do it.

Also, currently the way I'm saving is:

Set.Update(model);
Context.SaveChanges();

EDIT II: Where I'm including the related entities:

protected override IQueryable<A> GetQueryWithIncludes(Include level)
{
  var q = Query;
  if (level == Include.Detail)
  {
      q = q.Include(x => x.c).ThenInclude(y => y.d);
      q = q.Include(x => x.b);
  }
  return q;
}

My update method:

public A Update(A update)
{
// Commented is current fix
// update.b = null;
// update.c = null;
Update(update, true);
return update;
}

public void Update(Model model, bool save)
{
  SetQuery();
  Set.Update(model); //Set is DbSet
  if (save)
  {
    Context.SaveChanges(); // Context is DBContext
  }
}

START OF ORIGINAL THREAD:

I have a Database-first application/API. The model can be simplified(there are move navigational properties) to:

public class A
{
    // some properties
    public int SomeValue {get; set;}

    // navigational properties
    public virtual B b {get; set;}
    public virtual C c {get; set;}
}

public class B
{
    // some properties

    // navigational properties
    public virtual D d {get; set;}
}

public class C
{
    //some properties
}

In my repository query to get class A, I'm including the properties B, C, D and so on.

The properties are used to create DTOs and so on.

The problem arises when trying to update an entity of class A. The database has triggers that are used for logging. When updating class A, there are appearing log entries(entities are unaltered) for changes to each of the navigational properties' tables. As an example, if I get an entity of A, and update the value of SomeValue, there will be changes to the tables for B, C and D.

The classes B, C and D in this case are never edited, and are only used to create DTOs and connecting relationships between entities.

How can I save changes to an entity of A without touching B, C, D and thus not trigger the database to make a log entry?

I have tried AsNoTracking() after the ".Include().thenInclude()..." part without success.

0

There are 0 best solutions below