1

我最近更改了让用户在我的网站中输入日期的方式。它曾经是一个文本框,他们将其输入,但在收到反馈后,似乎人们更愿意将 3 个下拉菜单设置为 DD MM YYYY。我已经使用我在 SO 上找到的一些代码将此添加到我的网站中。

为了实现它,我必须创建一个类来绕过无效数据验证,我的类看起来像这样

public class DateSelector : ICustomMappings {
    public DateSelector() : this(System.DateTime.MinValue) { }
    public DateSelector(DateTime date) {
        Year = date.Year;
        Month = date.Month;
        Day = date.Day;
    }

    [Required]
    public int Year { get; set; }

    [Required, Range(1, 12)]
    public int Month { get; set; }

    [Required, Range(1, 31)]
    public int Day { get; set; }

    public DateTime? DateTime {
        get {
            DateTime date;
            if (!System.DateTime.TryParseExact(string.Format("{0}/{1}/{2}", Year, Month, Day), "yyyy/M/d", CultureInfo.InvariantCulture, DateTimeStyles.None, out date))
                return null;
            else
                return date;
        }
    }

    public void CreateMappings(IConfiguration configuration) {
        configuration.CreateMap<DateTime, DateSelector>()
            .ForMember(dest=>dest.DateTime,opt=>opt.Ignore())
            .ForMember(dest => dest.Day, opt => opt.MapFrom(src => src.Day))
            .ForMember(dest => dest.Month, opt => opt.MapFrom(src => src.Month))
            .ForMember(dest => dest.Year, opt => opt.MapFrom(src => src.Year));
    }
}

Automapper 在它是一个文本框时效果很好,但现在我将它拆分为下拉列表,我收到以下错误。

没有为“System.DateTime”和“System.Object”类型定义二元运算符 NotEqual。

我想我明白了,因为它试图将 DateTime 映射到我的班级,我该如何解决这个问题?

编辑:这是我的控制器,它调用一个方法从我的数据库中获取数据,然后使用扩展方法 .Project()

public ActionResult EditYoungPerson(int youngPersonId) {

    YoungPerson.EditYoungPersonViewModel editYoungPersonViewModel = new YoungPerson.EditYoungPersonViewModel();

    editYoungPersonViewModel.YoungPerson = Context.GetYoungPersonDetailsForYoungPersonId(youngPersonId).Project().To<YoungPerson._YoungPersonViewModel>().Single();

    return View(editYoungPersonViewModel);
}

这是堆栈跟踪

[InvalidOperationException: The binary operator NotEqual is not defined for the types 'System.DateTime' and 'System.Object'.]
System.Linq.Expressions.Expression.GetEqualityComparisonOperator(ExpressionType binaryType, String opName, Expression left, Expression right, Boolean liftToNull) +4026223
System.Linq.Expressions.Expression.NotEqual(Expression left, Expression right) +73
AutoMapper.QueryableExtensions.Extensions.BindMappedTypeExpression(IMappingEngine mappingEngine, PropertyMap propertyMap, ExpressionResolutionResult result, MemberInfo destinationMember, IDictionary`2 typePairCount) +268
AutoMapper.QueryableExtensions.Extensions.CreateMemberBindings(IMappingEngine mappingEngine, TypePair typePair, TypeMap typeMap, Expression instanceParameter, IDictionary`2 typePairCount) +1477
AutoMapper.QueryableExtensions.Extensions.CreateMapExpression(IMappingEngine mappingEngine, TypePair typePair, Expression instanceParameter, IDictionary`2 typePairCount) +363
AutoMapper.QueryableExtensions.Extensions.CreateMapExpression(IMappingEngine mappingEngine, TypePair typePair, IDictionary`2 typePairCount) +119
AutoMapper.QueryableExtensions.<>c__DisplayClass1`2.<CreateMapExpression>b__0(TypePair tp) +119
System.Collections.Concurrent.ConcurrentDictionary`2.GetOrAdd(TKey key, Func`2 valueFactory) +85
AutoMapper.Internal.ConcurrentDictionaryImpl`2.GetOrAdd(TKey key, Func`2 valueFactory) +67
AutoMapper.QueryableExtensions.Extensions.CreateMapExpression(IMappingEngine mappingEngine) +322
AutoMapper.QueryableExtensions.ProjectionExpression`1.To() +111
Portal.Controllers.YoungPersonController.EditYoungPerson(Int32 youngPersonId) in c:\tfs\Portal\Dev\Portal.UI\Controllers\YoungPersonController.cs:278
lambda_method(Closure , ControllerBase , Object[] ) +161
System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters) +14
System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters) +208
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +27
System.Web.Mvc.Async.<>c__DisplayClass42.<BeginInvokeSynchronousActionMethod>b__41() +28
System.Web.Mvc.Async.<>c__DisplayClass8`1.<BeginSynchronous>b__7(IAsyncResult _) +10
System.Web.Mvc.Async.WrappedAsyncResult`1.End() +57
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult) +48
System.Web.Mvc.Async.<>c__DisplayClass39.<BeginInvokeActionMethodWithFilters>b__33() +57
System.Web.Mvc.Async.<>c__DisplayClass4f.<InvokeActionMethodFilterAsynchronously>b__49() +223
System.Web.Mvc.Async.<>c__DisplayClass37.<BeginInvokeActionMethodWithFilters>b__36(IAsyncResult asyncResult) +10
System.Web.Mvc.Async.WrappedAsyncResult`1.End() +57
  System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethodWithFilters(IAsyncResult asyncResult) +48
System.Web.Mvc.Async.<>c__DisplayClass2a.<BeginInvokeAction>b__20() +24
System.Web.Mvc.Async.<>c__DisplayClass25.<BeginInvokeAction>b__22(IAsyncResult asyncResult) +102
System.Web.Mvc.Async.WrappedAsyncResult`1.End() +57
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult) +43
System.Web.Mvc.<>c__DisplayClass1d.<BeginExecuteCore>b__18(IAsyncResult asyncResult) +14
System.Web.Mvc.Async.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar) +23
System.Web.Mvc.Async.WrappedAsyncResult`1.End() +62
System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +57
System.Web.Mvc.Async.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar) +23
System.Web.Mvc.Async.WrappedAsyncResult`1.End() +62
System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +47
        System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.EndExecute(IAsyncResult asyncResult) +10
System.Web.Mvc.<>c__DisplayClass8.<BeginProcessRequest>b__3(IAsyncResult asyncResult) +25
System.Web.Mvc.Async.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar) +23
System.Web.Mvc.Async.WrappedAsyncResult`1.End() +62
System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +47
System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +9
    System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +9651116
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155

编辑:我错过了使用 DataSelector 类的 ViewModel。

        public class _YoungPersonViewModel ICustomMappings {

        public int YoungPersonId { get; set; }
        public string FirstName { get; set; }
        public string Surname { get; set; }
        public string FullName { get { return FirstName + " " + Surname; } }
        public DateSelector DateOfBirth { get; set; }
        public IEnumerable<SelectListItem> GenderTypeList { get; set; }

        public void CreateMappings(IConfiguration configuration) {
            configuration.CreateMap<Entities.Models.YoungPerson, _YoungPersonViewModel>()

                .ForMember(dest => dest.DateOfBirth, opt=>opt.MapFrom(src=>src.DateOfBirth));
        }
    }
4

1 回答 1

1

尝试使用 ProjectUsing:

configuration.CreateMap<DateTime, DateSelector>()
    . ProjectUsing(src => new DateSelector(src));

?

于 2015-01-06T17:48:43.430 回答