无法使 DelegateDecompiler 中的 ShouldDecompile 配置正常工作

Can't get ShouldDecompile configuration in DelegateDecompiler to work

我正在尝试为 DelegateDecompiler to work, as shown here: http://daveaglick.com/posts/computed-properties-and-entity-framework 获取自动反编译配置 但它不起作用:(

不确定我做错了什么。

这是具有计算值的 class。

public class Person
{
    public int Id { get; set; }
    public string First { get; set; }
    public string Last { get; set; }

    [NotMapped]
    [Computed]
    public string Full { get { return First + " " + Last; } }
}

这是配置。

public class DelegateDecompilerConfiguration : DefaultConfiguration
{
    public override bool ShouldDecompile(MemberInfo memberInfo)
    {
        // Automatically decompile all NotMapped members
        return base.ShouldDecompile(memberInfo) || memberInfo.GetCustomAttributes(typeof(NotMappedAttribute), true).Length > 0;
    }
}

我也试过删除[NotMapped],然后在上面的配置中将typeof(NotMappedAttribute)更改为typeof(ComputedAttribute)

那我就这样注册了

DelegateDecompiler.Configuration.Configure(new DelegateDecompilerConfiguration());

在Startup.cs。我也试过直接把它放到我的动作中。

public ActionResult Test()
{
    DelegateDecompiler.Configuration.Configure(new DelegateDecompilerConfiguration());

    var ctx = new ApplicationDbContext();
    var result = ctx.People.Where(x => x.Full.Contains("foo bar")).ToList();

    return View();
}

两个都不行:(

如果我将 .Decompile() 放在查询上,那么它会按预期工作。所以 DelegateDecompiler 正在工作,但不是配置。

正如您在 GitHub 问题中发现的那样,您始终必须在 LINQ 查询中调用 .Decompile()。额外的配置只是消除了使用 Computed 属性修饰所有计算属性的需要,而不是依赖于 Entity Framework NotMapped 属性。

正如 Dave 所说,它需要 Decompile()

因此您不必记住调用它,您可以创建一个映射器扩展来包装您正在做的事情。

public static class MapperExtensions
{
    /// <summary>
    /// Creates a list from automapper projection. Also wraps delegate decompiler to supprt Computed Domain properties
    /// </summary>
    /// <typeparam name="TDestination"></typeparam>
    /// <param name="projectionExpression"></param>
    /// <returns></returns>
    public static List<TDestination>
        ToList<TDestination>(this IProjectionExpression projectionExpression)
    {
        return projectionExpression.To<TDestination>().Decompile().ToList();
    }
}