简体   繁体   English

尝试从int映射时无效的强制转换异常? 枚举?

[英]Invalid cast exception when trying to map from int? to enum?

I have a senario where a user wants to select his gender which is not a mandatory field. 我有一个senario,用户想要选择他的性别,而不是必填字段。 Here in my ui the gender is listed in dropdownlist which has two options Male and Female and has a optional label Gender . 在我的ui中,性别列在dropdownlist中,它有两个选项MaleFemale,并且有一个可选的标签Gender But the Gender is a enum in my project , so if the user did not select any gender a null value must be entered into the database, But unfortunately iam not able to do it due to some cast exception Can any body give me a help in resolving this? 但是性别是我项目中的枚举,所以如果用户没有选择任何性别,则必须在数据库中输入空值,但遗憾的是由于某些强制转换异常,我无法做到这一点可以任何机构给我一个帮助解决这个问题?

I was using petapoco as my orm so my user entity looks like this 我使用petapoco作为我的用户,所以我的用户实体看起来像这样

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using Helpers;
using PetaPoco;
using StructureMap;

[TableName("User")]
[PrimaryKey("UserId")]
[ExplicitColumns]
public class User
{
    [Column("UserId")]
    public int Id { get; set; }

    [Column]
    [Required]
    public Guid Identifier { get; set; }

    [Column("UserStatusId")]
    [Required]
    public UserStatus UserStatus { get; set; }

    [Column]
    [Required]
    public int RoleId { get; set; }

    [Column]
    public int? SchoolId { get; set; }

    [Column]
    public int? LanguageId { get; set; }

    [Column("TitleId")]
    [Required]
    public Title Title { get; set; }

    [Column("GenderId")]
    [Required]
    public Gender? Gender { get; set; }

    [Column]
    [Required]
    [StringLength(35)]
    public string Username { get; set; }

    [StringLength(100)]
    public string Password { get; set; }

    [Column]
    [StringLength(100)]
    public string PasswordEncrypted { get; set; }

    [Column]
    [StringLength(10)]
    public string PasswordSalt { get; set; }

    [Column]
    [Required]
    [DataType(DataType.EmailAddress)]
    [StringLength(255)]
    public string Email { get; set; }

    [Column]
    [Required]
    [StringLength(35)]
    public string FirstName { get; set; }

    [Column]
    [Required]
    [StringLength(35)]
    public string LastName { get; set; }

    public string FullName { 
        get
        {
            return string.Concat(FirstName, " ", LastName);
        }
    }

    [Column]
    public DateTime? DateOfBirth { get; set; }

    [Column]
    public bool Subscribed { get; set; }

    [Column]
    public bool TermsAgreed { get; set; }

    [Column]
    public DateTime? TermsAgreedDate { get; set; }

    [Column]
    public DateTime CreatedDate { get; set; }

    [Column]
    public DateTime ModifiedDate { get; set; }

    [Column]
    public DateTime? LoginDate { get; set; }

    public Role Role { get; set; }

    public School School { get; set; }

    public Language Language { get; set; }
}

My gender enum is like this 我的性别枚举是这样的

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;

public enum Gender
{
    /// <summary>
    /// Male
    /// </summary>
    [Description("Male")]
    Male = 1,

    /// <summary>
    /// Female
    /// </summary>
    [Description("Female")]
    Female
}

and my view model looks like this 我的视图模型看起来像这样

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Web.Mvc;

/// <summary>
/// Model for edit view model user
/// </summary>
public class UserEditViewModel
{
    /// <summary>
    /// Gets or sets the User id
    /// </summary>
    public int Id { get; set; }

    /// <summary>
    /// Gets or sets Title Id
    /// </summary>
    public int UserTitle { get; set; }

    /// <summary>
    /// Gets or sets the school Name
    /// </summary>
    public string Username { get; set; }

    /// <summary>
    /// Gets or sets the School first name
    /// </summary>
    public string FirstName { get; set; }

    /// <summary>
    /// Gets or sets the school last name
    /// </summary>
    public string LastName { get; set; }

    /// <summary>
    /// Gets or sets the school address line1
    /// </summary>
    public string Password { get; set; }

    /// <summary>
    /// Gets or sets the school address line2
    /// </summary>        
    public string ConfirmPassword { get; set; }

    /// <summary>
    /// Gets or sets the email address of the school
    /// </summary>
    public string Email { get; set; }

    /// <summary>
    /// Gets or sets the  created date
    /// </summary>
    public DateTime CreatedDate { get; set; }

    /// <summary>
    /// Gets or sets user status id
    /// </summary>
    public int UserStatus { get; set; }

    /// <summary>
    /// Gets or sets SchoolName
    /// </summary>
    public string SchoolDetails { get; set; }

    /// <summary>
    /// Gets or sets Language Id
    /// </summary>
    public int LanguageId { get; set; }

    /// <summary>
    /// Gets or sets Langauge list
    /// </summary>
    public IList<Language> Langauges { get; set; }

    /// <summary>
    /// Gets or sets RoleId
    /// </summary>        
    public int RoleId { get; set; }

    /// <summary>
    /// Gets or sets SchoolId
    /// </summary>
    public int SchoolId { get; set; }

    /// <summary>
    /// Gets or sets DateOfBirth
    /// </summary>
    public DateTime DateOfBirth { get; set; }

    /// <summary>
    /// Gets or sets Gender
    /// </summary>
    public int? Gender { get; set; }

    /// <summary>
    /// Gets UserGender list 
    /// </summary>
    public Dictionary<int, string> Genders
    {
        get
        {
            var listitems = new Dictionary<int, string>();
            foreach (Gender r in Enum.GetValues(typeof(Gender)))
            {
                listitems.Add((int)r, r.ToString());
            }

            return listitems;
        }
    }

    /// <summary>
    /// Gets Title list
    /// </summary>
    public Dictionary<int, string> Titles
    {
        get
        {
            var listitems = new Dictionary<int, string>();
            foreach (Title r in Enum.GetValues(typeof(Title)))
            {
                listitems.Add((int)r, r.ToString());
            }

            return listitems;
        }
    }

    /// <summary>
    /// Gets UserStatus list 
    /// </summary>
    public Dictionary<int, string> UserStatuses
    {
        get
        {
            var listitems = new Dictionary<int, string>();
            foreach (UserStatus r in Enum.GetValues(typeof(UserStatus)))
            {
                listitems.Add((int)r, r.ToString());
            }

            return listitems;
        }
    }

    /// <summary>
    /// Gets or sets a value indicating whether Subscribed
    /// </summary>
    public bool Subscribed { get; set; }

    /// <summary>
    /// Gets or sets a value indicating whether TermsAgreed
    /// </summary>
    public bool TermsAgreed { get; set; }
}

And i was using automapper to map from User to UserEditviewModel and vice versa like this 我正在使用automapper从User映射到UserEditviewModel,反之亦然

   Mapper.CreateMap<User, UserEditViewModel>().ForMember(
           dest => dest.Langauges, opt => opt.Ignore()).ForMember(
           dest => dest.Password, opt => opt.Ignore()).ForMember(
           dest => dest.ConfirmPassword, opt => opt.Ignore()).ForMember(
           dest => dest.SchoolDetails, opt => opt.MapFrom(src =>
               (!string.IsNullOrEmpty(src.School.SchoolDetails.Region)) ?
               string.Concat(src.School.Name, ", ",
               src.School.SchoolDetails.City, ", ",
               src.School.SchoolDetails.Region, ", ",
               src.School.SchoolDetails.PostalCode) :
               string.Concat(src.School.Name, ", ",
               src.School.SchoolDetails.City, ", ",
               src.School.SchoolDetails.PostalCode))).ForMember(
          dest => dest.Titles, opt => opt.Ignore()).ForMember(
          dest => dest.UserStatuses, opt => opt.Ignore()).ForMember(
          dest => dest.UserTitle, opt => opt.MapFrom(src => src.Title)).ForMember(
          dest => dest.Genders, opt => opt.Ignore()).ForMember(
          dest => dest.Gender, opt => opt.MapFrom(src =>
              src.Gender == null ? (int?)null : (int)src.Gender));            

 Mapper.CreateMap<UserEditViewModel, User>().ForMember(
            dest => dest.Username, opt => opt.MapFrom(src =>
                HttpUtility.HtmlDecode(src.Username))).ForMember(
            dest => dest.FirstName, opt => opt.MapFrom(src =>
                HttpUtility.HtmlDecode(src.FirstName))).ForMember(
            dest => dest.LastName, opt => opt.MapFrom(src =>
                HttpUtility.HtmlDecode(src.LastName))).ForMember(
            dest => dest.Password, opt => opt.MapFrom(src =>
                HttpUtility.HtmlDecode(src.Password))).ForMember(
            dest => dest.Email, opt => opt.MapFrom(src =>
                HttpUtility.HtmlDecode(src.Email))).ForMember(
            dest => dest.Role, opt => opt.Ignore()).ForMember(
            dest => dest.RoleId, opt => opt.Ignore()).ForMember(
            dest => dest.ModifiedDate, opt => opt.Ignore()).ForMember(
            dest => dest.School, opt => opt.Ignore()).ForMember(
            dest => dest.Language, opt => opt.Ignore()).ForMember(
            dest => dest.LoginDate, opt => opt.Ignore()).ForMember(
            dest => dest.PasswordEncrypted, opt => opt.Ignore()).ForMember(
            dest => dest.PasswordSalt, opt => opt.Ignore()).ForMember(
            dest => dest.TermsAgreedDate, opt => opt.Ignore()).ForMember(
            dest => dest.Identifier, opt => opt.Ignore()).ForMember(
            dest => dest.Title, opt => opt.MapFrom(src => src.UserTitle)).ForMember(
            dest => dest.Gender, opt => opt.MapFrom( src =>
                src.Gender == null ? (Gender?)null : (Gender)src.Gender));

But after doing all this iam getting exception like this Invalid cast from 'System.Int32' to 'System.Nullable`1 但是在完成所有这些之后我会遇到异常,例如从'System.Int32'到'System.Nullable`1的无效转换

Can anybody help? 有人可以帮忙吗?

A rat's nest. 一只老鼠的巢。 But I would bet you have to change this code 但我敢打赌你必须改变这段代码

(int)src.Gender

to

(int?)src.Gender

Or the full line (both places you do it) 或者全线(你做的两个地方)

dest => dest.Gender, opt => opt.MapFrom(src =>
          src.Gender == null ? (int?)null : (int?)src.Gender));  

public int? Gender { get; set; }

this line declares gender as nullable int 此行将gender声明为nullable int

(int)src.Gender line tries to cast as int (int)src.Gender行尝试转换为int

For debug sake, ignore Gender mapping 出于调试原因,请忽略性别映射

dest => dest.Gender, opt => opt.Ignore()

But I think the problem is in SchoolId and LanguageId, you should map them properly. 但我认为问题出在SchoolId和LanguageId中,你应该正确映射它们。
All necessary information about fault mapping should be in stack trace. 有关故障映射的所有必要信息都应该在堆栈跟踪中。

Any particular reason why you're not using the Enum in your model? 您在模型中没有使用Enum的任何特殊原因?

I always do that, and have no problems, with the Flag Enum Model Binder MVC even handles flag enums without a bother! 我总是这样做,并没有任何问题,使用Flag Enum Model Binder MVC甚至可以毫不费力地处理标志枚举!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 投 <int> 。投 <int?> 应用于通用枚举集合会导致无效的强制转换异常 - Cast<int>.Cast<int?> applied on generic enum collection results in invalid cast exception 使用反射从“System.Int32”到枚举的无效转换 - Invalid cast from 'System.Int32' to Enum using reflections InvalidCastException尝试从装箱的int强制转换为可为空的枚举 - InvalidCastException trying to cast from a boxed int to a nullable enum int上的无效转换异常为double - invalid cast exception on int to double 无效的转换异常从smallint转换为Int32时? - Invalid Cast Exception While converting from smallint to Int32? Sqlite - Insert给出错误 - 无效的强制转换异常 - “从&#39;DateTime&#39;到&#39;Int32&#39;的无效强制转换。” - Sqlite - Insert gives error - Invalid cast exception - “Invalid cast from 'DateTime' to 'Int32'.” 尝试在绑定中转换用户控件的属性时,无效的强制转换异常 - Invalid Cast Exception when trying to convert a property of a user control in a binding 尝试在Unity上使用Oracle.DataAccess时无效的Cast Exception - Invalid Cast Exception when trying to use Oracle.DataAccess on Unity 在枚举属性的情况下从 System.Int32 到 Nullable 的无效转换 - Invalid cast from System.Int32 to Nullable in case of Enum properties 尝试从JSONData对象反序列化时,带有Unity和LitJSON的C#获得无效的Cast异常 - c# With Unity and LitJSON Getting an Invalid Cast Exception when trying to de-serialize back from JSONData object
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM