Testing with Entity Framework dbContext, and NoTracking option
This posting is provided "AS IS" with no warranties, and confers no rights. Use of included script samples are subject to the terms specified at https://www.microsoft.com/info/cpyright.htm
During unit or integration tests, which involve database modifications, the following pattern is often utilized -
var preChangeIntroducedValue = GetValueFromDB();
// introduce change
var postChangeIntoroducedValue = GetValueFromDB();
// Assert something about the relationship between pre and post values
If using Entity Framework for accessing database, it is important to remember that if the value in the database
changes between the calls to GetValueFromDB, Entity Framework will return the value originally placed into the
preChangeIntroduceValue, hence your tests will be probably fail, even though the logic might be correct. The reason
for this is the cashing/tracking mechanism built-in into Entity Framework. To address this use AsNoTracking
option as illustrated by the example below.
private static readonly FIMEntities FIMEntities = new FIMEntities();
public static bool TryToGetMVEntryByEmployeeID(string employeeID, out mms_metaverse mvEntryOut)
{
try
{
mvEntryOut = FIMEntities.mms_metaverse.AsNoTracking(). Single(mvEntry => mvEntry.employeeID == employeeID);
return true;
}
catch (Exception)
{
mvEntryOut = null;
return false;
}
}
References: