When accessing the navigation property of an entity that I've used AutoFixture to put into a test method, it changes non-navigation properties of the parent type that are related to the navigation property I accessed.
For example, if I had these two related entities, not related by convention but rather by attributes:
public class First
{
[Key]
public int FirstKey { get; set; }
public int SecondKey { get; set; }
public virtual Second Second { get; set; }
public string SomeOtherProperty { get; set; }
}
public class Second
{
[Key]
public int SecondKey { get; set; }
... other stuff
}
Then passing these through the ModelMetadataGenerator.LoadFromCoadFirstContext(...)
and customizing my fixture...
When I put it in a test, like so...
// Using NUnit 3 and NSubstitute
[Test]
[AutoNSubstituteData] //This is my custom class that adds the AutoFixture.NSubstitute customization
public void Test(First first)
{
var firstKey = first.FirstKey; //Returns an auto-generated number, say 10
var someOtherProperty = first.SomeOtherProperty; //Returns an auto-generated string, say "abc123"
var firstKeysSecondKey = first.SecondKey; //Returns, say, 105
var secondKey = first.Second.SecondKey; //Returns, say, 75
var afterAccessingNavigation = first.FirstKey; //Now returns 75
var anotherProperty = first.SomeOtherProperty; //Returns a different auto-generated string, say "123abc"
}
If that didn't make sense, basically when accessing navigation properties that have a relationship back to the accessing member, that member is re-generated completely.
Of course, this keeps the "integrity" of the property constraints, which is probably desired in most cases.
However, I might expect first.SecondKey
to remain 105, and the first.Second.SecondKey
to also be generated as 105, and SomeOtherProperty to not change from the original value.
Scouring through the metadata that ModelMetadataGenerator
created, I found it made these contraints:
OneToManyPropertyConstraint<Second,First>
PropInfo = ICollection<First>
_inverse = Second
The workaround is to access navigation properties up-front/immediately, as in make a first.Second.SecondKey
call first, and then reference/use/expect/test against/etc the other variables as they will no longer change.