UpdateGraph updating associated collection property with parent node

38 views Asked by At

After using UpdateGraph, if an associated collection has an attribute from the same class as the parent node, this attribute ends up being updated with a reference to the parent node.

The scenario is:

  • User class has an ICollection of Team.
  • Team has a property named CreatedBy (of type User).
  • After using UpdateGraph to add a collection of Teams to a certain user (user.Teams), every Team.CreatedBy is updated with the user that I'm using as parent node.

I created a fiddle for reproducing this problem: https://dotnetfiddle.net/iaC9MW

Anyway, here is the main code snippet for this problem:

var user = context.Users.AsNoTracking().FirstOrDefault(q => q.Name == "User_A");
var teams = context.Teams.AsNoTracking().Where(q => q.Name == "Team A").ToList();
user.Teams = teams;

context.UpdateGraph(user, map => map.AssociatedCollection(q => q.Teams));
context.SaveChanges();

So after using UpdateGraph/SaveChanges, "Team A".CreatedBy receives "User A", although I didn't specify that.

Here are the definitions of my classes

public class User
{
    public int Id { get; set; }
    public string Name { get; set; }
    public Boolean IsActive { get; set; }
    public ICollection<Team> Teams {get; set; }
}

public class Team 
{
    public int Id { get; set; }
    public string Name { get; set; }
    public User CreatedBy { get; set; }
}

My attempts:

  • I tried to use .Include() for the associated collection
  • I tried a few different approaches for adding this team collection.
  • I tried also to use List instead ICollection
  • I cannot use .OwnedCollection, since any Team may exist by themselves, they're not children of User. Even though, I tried to use that.

All of those attempts ended up on the same result, where Team.CreatedBy gets updated automatically.

If I don't update using GraphDiff, everything works well.

Is there anything wrong on my code? So far, I believe this is a bug on GraphDiff.

0

There are 0 answers