I have primitive obsession class EmailAddress
that has overridden ToString()
:
public class EmailAddress
{
private string _value;
public EmailAddress(string value)
{
_value = value;
}
public override string ToString()
{
return _value;
}
}
My domain model Customer
looks like:
public class Customer
{
public EmailAddress EmailAddress { get; set; }
public string FullName{ get; set; }
}
And I have configured conversion for EmailAddress
in FluentApi:
modelBuilder.Entity<Customer>().Property(x => x.EmailAddress)
.HasConversion(
x => x.ToString(),
x => new EmailAddress(x));
Also I have generic repository pattern, and when I want to filter data:
public List<Customer> GetCustomers(GetCustomersQuery queryParameters)
{
IQueryable<Customer> queryCustomers = _customerContext.GetAll();
return queryCustomers.Where(x =>
x.EmailAddress.ToString()
.Contains(queryParameters.Email)).ToList();
}
I have got an error:
The LINQ expression
DbSet<Customer>().Where(t => t.EmailAddress.ToString()
could not be translated. Additional information: Translation of methodobject.ToString
failed.
I've tried EF 6.4 Do you have any workaround?
CodePudding user response:
For really motivated, who doesn't afraid of complicated domain, I have found solution
public class EmailAddress
{
private string _value;
public static explicit operator string(EmailAddress emailAddress) => emailAddress._value;
public EmailAddress(string value)
{
_value = value;
}
public override string ToString()
{
return _value;
}
}
and query is
queryCustomers.Where(x =>
((string)x.EmailAddress)
.Contains(queryParameters.Email)).ToList();
this query is executing on server side.
CodePudding user response:
You can try like below:
return queryCustomers.Where(x =>
x.EmailAddress
.Contains(queryParameters.Email)).ToList();