【发布时间】:2020-10-26 16:25:09
【问题描述】:
我有这个作为我的模型(出于明显的原因进行了修改)
public class Model
{
public int Id {get; set;}
public string Data {get; set;}
public TypeDomainValue ModelType {get; set;}
}
ModelType 在数据库中仅作为字符串值已知(未连接表)。
但是,如果我想在 linq 语句中过滤 TypeDomainValue 的值
models.Where(c => c.ModelType.Value.Contains(searchString));
我收到无法翻译 Linq 表达式的错误。 我已经尝试使用 EF.Functions.Like 会产生类似的错误。 由于我不想将整个表加载到内存中,如何才能正确翻译它。
编辑: 我使用以下 ValueConverter
public class ModelTypeDomainValueConverter : ValueConverter<ModelTypeDomainValue, string>
{
public ModelTypeDomainValueConverter([CanBeNull] ConverterMappingHints mappingHints = null) : base(ConvertToString(), ConvertToDomainValue(), mappingHints)
{
}
private static Expression<Func<ModelTypeDomainValue, string>> ConvertToString()
{
return x => x.Value;
}
private static Expression<Func<string, ModelTypeDomainValue>> ConvertToDomainValue()
{
return x => ModelTypeDomainValue.CreateByValue(x);
}
}
添加以下扩展名:
public static ModelBuilder UseValueConverter(this ModelBuilder modelBuilder, ValueConverter converter)
{
var type = converter.ModelClrType;
foreach (var entityType in modelBuilder.Model.GetEntityTypes())
{
var properties = entityType.ClrType.GetProperties().Where(p => p.PropertyType == type);
foreach (var property in properties)
{
modelBuilder.Entity(entityType.Name).Property(property.Name).HasConversion(converter);
}
}
return modelBuilder;
}
【问题讨论】:
-
什么是
TypeDomainValue? -
具有值和描述的类。数据库中只有值是已知的。
-
您能否添加定义以及
Model的模型构建器是如何设置的? -
如果数据库中只知道
Value(可能是字符串,因为您使用的是Contains),并且您没有在Model中使用FK 属性 -为什么这是一个单独的实体?每当您将新的Model添加并保存到您的上下文时,这似乎您将遇到添加未跟踪的TypeDomainValue对象的新副本的问题。这种情况有些不对劲,我怀疑您需要重新考虑设计。 -
ModelTypeDomainValue 包含一些只有在应用程序中才知道的其他属性。我们将这些保留在数据库之外,因为数据库(和数据)归客户所有。
标签: c# linq .net-core entity-framework-core