I have the following C# class:
public class SomeClass{
public string Name;
public List<SomeClass> List1;
public List<SomeClass> List2;
}
When I have 2 instances of SomeClass (SomeClass1 and SomeClass2) and do something like:
SomeClass1.List1.Add(SomeClass2);
It also adds SomeClass1 to SomeClass2.List2 for some reason when context.SaveChanges() is called. How can I prevent this?
Edit: I am using code first.
Thanks
If you don’t have any mapping with Fluent API EF will create a mapping based on conventions. The convention in this case is that
List1andList2are the inverse navigation properties of the same relationship – in this case a “self-referencing” many-to-many relationship.The effect you experience is an automatic relationship fixup which is executed when
DetectChanges()is called (orSaveChanges()which callsDetectChanges()internally). This fixup updates inverse navigation properties of attached entities automatically so that they are consistent with each other. You cannot prevent this and it shouldn’t actually be a problem.Edit
If you don’t want a mapping between the two lists you must specify an explicit mapping with Fluent API. For example: If both lists belong to separate one-to-many relationships you must specify:
This mapping says that the second end of each relationship is not exposed in the model (hence
WithRequired()/WithOptional()without parameter).Similar you can specify two many-to-many relationships with
HasMany(s => s.List1/2).WithMany().Map(...).