简体   繁体   中英

How to use strongly typed id in in EF?

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 method object.ToString failed.

I've tried EF 6.4 Do you have any workaround?

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.

You can try like below:

  return queryCustomers.Where(x =>
         x.EmailAddress
        .Contains(queryParameters.Email)).ToList();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM