1

我的 Global.aspx 中有以下钩子

    protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();
        RegisterRoutes(RouteTable.Routes);
        AutoMapper.Mapper.CreateMap<FormCollection, Models.IAmACustomer>().ForAllMembers(form => form.ResolveUsing<Models.FormCollectionValueResolver<Models.IAmACustomer>>());
    }

在我的控制器中:

[HttpPost]
    public ActionResult Create(FormCollection formCollection)
    {

        var customer = AutoMapper.Mapper.Map<FormCollection,Models.IAmACustomer> (formCollection,null);
    }

此行执行但我的自定义解析器从未被调用。

解析器如下所示:

public class FormCollectionValueResolver<TDestination>:ValueResolver<FormCollection,TDestination>
{
//Code removed for brevity
}

应用程序编译并运行,但是没有自定义解析器,对象中没有任何内容,它只是创建一个带有异常抛出 get 访问器的模拟对象。

4

2 回答 2

0

您应该考虑完全放弃 FormCollection:

http://geekswithblogs.net/michelotti/archive/2009/10/25/asp.net-mvc-view-model-patterns.aspx

基本上,您将依赖强类型视图 + 为表单自定义创建的 ViewModel 类型。这些表单上有诸如验证属性之类的东西,因此您可以通过验证框架运行它们。如果它是有效的,那么你才从发布的表单中更新你的持久性模型。我们远离直接从发布的表单创建域对象。

于 2009-11-28T05:12:38.033 回答
0

never 被调用的原因FormCollectionValueResolver<Customer>是该ForAllMembers()方法迭代了您的所有属性映射,由该ForMember()方法定义,应用指定的成员选项。但是,在您提供的代码示例中,没有定义任何属性映射,因此解析器永远不会被调用。

这是如何ForAllMembers()使用该方法的示例。

[Test]
public void AutoMapperForAllMembersTest()
{
    Mapper.CreateMap<Source, Destination>()
        .ForMember(dest => dest.Sum, 
            opt => opt.ResolveUsing<AdditionResolver>())
        .ForMember(dest => dest.Difference,
            opt => opt.ResolveUsing<SubtractionResolver>())
        .ForAllMembers(opt => opt.AddFormatter<CustomerFormatter>());

    Source source = new Source();
    source.Expression = new Expression
    {
        LeftHandSide = 2,
        RightHandSide = 1
    };

    Destination destination = Mapper.Map<Source, Destination>(source);
    Assert.That(destination.Sum, Is.EqualTo("*3*"));
    Assert.That(destination.Difference, Is.EqualTo("*1*"));
}    

public class Expression
{
    public int LeftHandSide { get; set; }

    public int RightHandSide { get; set; }
}

public class Source
{
    public Expression Expression { get; set; }
}

public class Destination
{
    public string Sum { get; set; }

    public string Difference { get; set; }
}

public class AdditionResolver : ValueResolver<Source, int>
{
    protected override int ResolveCore(Source source)
    {
        Expression expression = source.Expression;
        return expression.LeftHandSide + expression.RightHandSide;
    }
}

public class SubtractionResolver : ValueResolver<Source, int>
{
    protected override int ResolveCore(Source source)
    {
        Expression expression = source.Expression;
        return expression.LeftHandSide - expression.RightHandSide;
    }
}

public class CustomerFormatter : IValueFormatter
{
    public string FormatValue(ResolutionContext context)
    {
        return string.Format("*{0}*", context.SourceValue);
    }
}
于 2009-11-26T22:27:57.190 回答