如何在 EF 中使用强类型 ID?
How to use strongly typed id in in EF?
我有原始的痴迷 class EmailAddress
已经覆盖 ToString()
:
public class EmailAddress
{
private string _value;
public EmailAddress(string value)
{
_value = value;
}
public override string ToString()
{
return _value;
}
}
我的域模型 Customer
看起来像:
public class Customer
{
public EmailAddress EmailAddress { get; set; }
public string FullName{ get; set; }
}
并且我在 FluentApi 中为 EmailAddress
配置了转换:
modelBuilder.Entity<Customer>().Property(x => x.EmailAddress)
.HasConversion(
x => x.ToString(),
x => new EmailAddress(x));
我还有通用存储库模式,当我想过滤数据时:
public List<Customer> GetCustomers(GetCustomersQuery queryParameters)
{
IQueryable<Customer> queryCustomers = _customerContext.GetAll();
return queryCustomers.Where(x =>
x.EmailAddress.ToString()
.Contains(queryParameters.Email)).ToList();
}
我有一个错误:
The LINQ expression DbSet<Customer>().Where(t => t.EmailAddress.ToString()
could not be translated. Additional
information: Translation of method object.ToString
failed.
我试过 EF 6.4 你有什么解决方法吗?
真正上进,不怕复杂的领域,我找到了解决方案
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;
}
}
查询是
queryCustomers.Where(x =>
((string)x.EmailAddress)
.Contains(queryParameters.Email)).ToList();
此查询正在服务器端执行。
我有原始的痴迷 class EmailAddress
已经覆盖 ToString()
:
public class EmailAddress
{
private string _value;
public EmailAddress(string value)
{
_value = value;
}
public override string ToString()
{
return _value;
}
}
我的域模型 Customer
看起来像:
public class Customer
{
public EmailAddress EmailAddress { get; set; }
public string FullName{ get; set; }
}
并且我在 FluentApi 中为 EmailAddress
配置了转换:
modelBuilder.Entity<Customer>().Property(x => x.EmailAddress)
.HasConversion(
x => x.ToString(),
x => new EmailAddress(x));
我还有通用存储库模式,当我想过滤数据时:
public List<Customer> GetCustomers(GetCustomersQuery queryParameters)
{
IQueryable<Customer> queryCustomers = _customerContext.GetAll();
return queryCustomers.Where(x =>
x.EmailAddress.ToString()
.Contains(queryParameters.Email)).ToList();
}
我有一个错误:
The LINQ expression
DbSet<Customer>().Where(t => t.EmailAddress.ToString()
could not be translated. Additional information: Translation of methodobject.ToString
failed.
我试过 EF 6.4 你有什么解决方法吗?
真正上进,不怕复杂的领域,我找到了解决方案
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;
}
}
查询是
queryCustomers.Where(x =>
((string)x.EmailAddress)
.Contains(queryParameters.Email)).ToList();
此查询正在服务器端执行。