gpt4 book ai didi

c# - 使用 ExpressionVisitor 修改表达式以进行自动翻译

转载 作者:太空宇宙 更新时间:2023-11-03 23:39:55 39 4
gpt4 key购买 nike

我正在尝试在我的 Entity Framework 模型中添加对多语言分类字符串的支持。这是我的:

实体:

public partial class ServiceState : ITranslatableEntity<ServiceStateTranslation>
{
public int Id { get; set; }

public string Name { get; set; }

public virtual ICollection<ServiceStateTranslation> Translations { get; set; }
}

ITranslatableEntity 接口(interface):

public interface ITranslatableEntity<T>
{
ICollection<T> Translations { get; set; }
}

然后是包含翻译的实体:

public partial class ServiceStateTranslation
{
public int Id { get; set; }

[Index("IX_ClassificationTranslation", 1, IsUnique = true)]
public int MainEntityId { get; set; }

public ServiceState MainEntity { get; set; }

[Index("IX_ClassificationTranslation", 2, IsUnique = true)]
public string LanguageCode { get; set; }

public string Name { get; set; }
}

包含本地化字符串的属性的名称在主实体和翻译实体中始终相同(在本例中为 Name)。

使用这样的模型我可以做这样的事情:

var result = query.Select(x => new
{
Name = x.Name,
StateName =
currentLanguageCode == DEFAULTLANGUAGECODE
? x.ServiceState.Name
: x.ServiceState.Translations.Where(i => i.LanguageCode == currentLanguageCode)
.Select(i => i.Name)
.FirstOrDefault() ?? x.ServiceState.Name
}).ToList();

问题是我不喜欢为包含任何可翻译实体的每个查询编写这种代码,所以我正在考虑使用 QueryInterceptor和一个 ExpressionVisitor这会产生一些魔力,让我可以用这样的东西替换查询:

var result = query.Select(x => new
{
Name = x.Name,
StateName = x.ServiceState.Name
}).ToLocalizedList(currentLanguageCode, DEFAULTLANGUAGECODE);

我想可以创建一个 ExpressionVisitor 来:

  • 只改变Select里面的表达式实现 ITranslatableEntity<> 的导航属性 block 界面
  • 如果当前语言不是默认语言,改变表达式x.ServiceState.Name

    x.ServiceState.Translations.Where(i => i.LanguageCode == currentLanguageCode)
    .Select(i => i.Name)
    .FirstOrDefault() ?? x.ServiceState.Name

但我对 expression visitors 和 trees 不是很熟悉,所以我有点迷路了。有人能让我走上正轨吗?

最佳答案

好的,看来我已经想出了一个可行的解决方案。

public class ClassificationTranslationVisitor : ExpressionVisitor
{
private string langCode = "en";
private string defaultLangCode = "en";
private string memberName = null;
private Expression originalNode = null;

public ClassificationTranslationVisitor(string langCode, string defaultLanguageCode)
{
this.langCode = langCode;
this.defaultLangCode = defaultLanguageCode;
}

protected override Expression VisitParameter(ParameterExpression node)
{
if (langCode == defaultLangCode)
{
return base.VisitParameter(node);
}

if (!node.Type.GetCustomAttributes(typeof(TranslatableAttribute), false).Any() && originalNode == null)
{
return base.VisitParameter(node);
}

if (IsGenericInterface(node.Type, typeof(ITranslatableEntity<>)))
{
return AddTranslation(node);
}

return base.VisitParameter(node);
}

protected override Expression VisitMember(MemberExpression node)
{
if (node == null || node.Member == null || node.Member.DeclaringType == null)
{
return base.VisitMember(node);
}

if (langCode == defaultLangCode)
{
return base.VisitMember(node);
}

if (!node.Member.GetCustomAttributes(typeof(TranslatableAttribute), false).Any() && originalNode == null)
{
return base.VisitMember(node);
}

if (IsGenericInterface(node.Member.DeclaringType, typeof(ITranslatableEntity<>)))
{
memberName = node.Member.Name;
originalNode = node;
return Visit(node.Expression);
}

if (IsGenericInterface(node.Type, typeof(ITranslatableEntity<>)))
{
return AddTranslation(node);
}

return base.VisitMember(node);
}

private Expression AddTranslation(Expression node)
{
var expression = Expression.Property(node, "Translations");
var resultWhere = CreateWhereExpression(expression);
var resultSelect = CreateSelectExpression(resultWhere);
var resultIsNull = Expression.Equal(resultSelect, Expression.Constant(null));
var testResult = Expression.Condition(resultIsNull, originalNode, resultSelect);
memberName = null;
originalNode = null;
return testResult;
}

private Expression CreateWhereExpression(Expression ex)
{
var type = ex.Type.GetGenericArguments().First();
var test = CreateExpression(t => t.LanguageCode == langCode, type);
if (test == null)
return null;
return Expression.Call(typeof(Enumerable), "Where", new[] { type }, ex, test);
}

private Expression CreateSelectExpression(Expression ex)
{
var type = ex.Type.GetGenericArguments().First();

ParameterExpression itemParam = Expression.Parameter(type, "lang");
Expression selector = Expression.Property(itemParam, memberName);
var columnLambda = Expression.Lambda(selector, itemParam);

var result = Expression.Call(typeof(Enumerable), "Select", new[] { type, typeof(string) }, ex, columnLambda);
var stringResult = Expression.Call(typeof(Enumerable), "FirstOrDefault", new[] { typeof(string) }, result);
return stringResult;
}

/// <summary>
/// Adapt a QueryConditional to the member we're currently visiting.
/// </summary>
/// <param name="condition">The condition to adapt</param>
/// <param name="type">The type of the current member (=Navigation property)</param>
/// <returns>The adapted QueryConditional</returns>
private LambdaExpression CreateExpression(Expression<Func<ITranslation, bool>> condition, Type type)
{
var lambda = (LambdaExpression)condition;
var conditionType = condition.GetType().GetGenericArguments().First().GetGenericArguments().First();
// Only continue when the condition is applicable to the Type of the member
if (conditionType == null)
return null;
if (!conditionType.IsAssignableFrom(type))
return null;

var newParams = new[] { Expression.Parameter(type, "bo") };
var paramMap = lambda.Parameters.Select((original, i) => new { original, replacement = newParams[i] }).ToDictionary(p => p.original, p => p.replacement);
var fixedBody = ParameterRebinder.ReplaceParameters(paramMap, lambda.Body);
lambda = Expression.Lambda(fixedBody, newParams);

return lambda;
}

private bool IsGenericInterface(Type type, Type interfaceType)
{
return type.GetInterfaces().Any(x =>
x.IsGenericType &&
x.GetGenericTypeDefinition() == interfaceType);
}
}

public class ParameterRebinder : ExpressionVisitor
{
private readonly Dictionary<ParameterExpression, ParameterExpression> map;

public ParameterRebinder(Dictionary<ParameterExpression, ParameterExpression> map)
{
this.map = map ?? new Dictionary<ParameterExpression, ParameterExpression>();
}

public static Expression ReplaceParameters(Dictionary<ParameterExpression, ParameterExpression> map, Expression exp)
{
return new ParameterRebinder(map).Visit(exp);
}

protected override Expression VisitParameter(ParameterExpression node)
{
ParameterExpression replacement;

if (map.TryGetValue(node, out replacement))
node = replacement;

return base.VisitParameter(node);
}
}

我还添加了 TranslatableAttribute,这是任何要翻译的属性所必需的。

代码当然缺少一些检查,但它已经在我的环境中运行了。我也没有检查被替换的表达式是否在 Select block 内,但看起来 TranslatableAttribute 没有必要。

我使用了 ParameterRebinder 和这个答案中的一些其他代码 ExpressionVisitor soft delete

关于c# - 使用 ExpressionVisitor 修改表达式以进行自动翻译,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29410428/

39 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com