ValueObject GetEqualityComponents not applied when obtaining items from the database
jbloem9 opened this issue · 1 comments
First Issue:
I am wanting to see if an inspector exists in the database by searching for the inspector code.
I am using the following code;
var inspectorDb = breedItContext.Inspectors.FirstOrDefault(insp => insp.ParticipantCode.Value == inspectorCode);
Here the inspectorCode is an input. The ParticipantCode is a ValueObject (Code is supplied below).
I am getting the following error at runtime;
Second Issue
Due to the above error I refactored the code to first create a participant code and then compare a participant code with a database participant code. Then I got another issue.
When running this code;
var ptCode = ParticipantCode.Create("ABCD").Value; //db value is abcd
var inspectorDb = breedItContext.Inspectors.FirstOrDefault(insp => insp.ParticipantCode == ptCode);
Returns null.
But when running this code;
var ptCode = ParticipantCode.Create("abcd").Value;
var inspectorDb = breedItContext.Inspectors.FirstOrDefault(insp => insp.ParticipantCode == ptCode);
Returns the inspector.
I have a GetEqualityComponents that converts the code to uppercase and my expectation is that both the database value and the ParticipantCode created here would be converted to uppercase. And as such my expectation is that both of the above snippets should return and inspector.
My class is as follows;
public class ParticipantCode : ValueObject
{
///
/// Initializes a new instance of the class.
///
protected ParticipantCode()
{
}
private ParticipantCode(string value)
{
Value = value;
}
/// <summary>
/// Gets the participant code raw value.
/// </summary>
public virtual string Value { get; } = string.Empty;
/// <summary>
/// Creates the participant code.
/// </summary>
/// <param name="code">The participant code.</param>
/// <returns>The result of the participant code creation.</returns>
public static Result<ParticipantCode> Create(string code)
{
return new ParticipantCode(code);
}
/// <summary>
/// Gets the equality components.
/// </summary>
/// <returns>The components to determine ParticipantCode equality.</returns>
protected override IEnumerable<object> GetEqualityComponents()
{
yield return Value.ToUpper();
}
}
EF Core doesn't know about the GetEqualityComponents
method, and can't inject it into the generated SQL. In the SQL profiler, look at the query EF generates, most likely adding .ToUpper()
as in insp.ParticipantCode.ToUpper() == ptCode.ToUpper()
will help.