简体   繁体   English

实体框架 | 错误:InvalidCastException:System.Int32 类型的字段必须是字符串、数组或 ICollection 类型

[英]Entity Framework | Error: InvalidCastException: The field of type System.Int32 must be a string, array or ICollection type

Issue问题

I'm receiving the following error when I submit (or post) a request to my Home Controller, for a method called NewsletterSignup.当我向我的 Home Controller提交(或发布)一个名为 NewsletterSignup 的方法的请求时,我收到以下错误。 The error is prompted after my newsletter form is submitted and prior to when this method is called and the object, capturing form data, is created, creating a situation where it's difficult to troubleshoot, and identify where this exact issue is propagating.在我的时事通讯表单提交后以及调用此方法并创建捕获表单数据的 object 之前提示错误,从而造成难以排除故障的情况,并确定此确切问题正在传播的位置。

Error错误

An unhandled exception occurred while processing the request.处理请求时发生未处理的异常。

InvalidCastException : The field of type System.Int32 must be a string, array or ICollection type. InvalidCastException : System.Int32 类型的字段必须是字符串、数组或 ICollection 类型。 ... System.ComponentModel.DataAnnotations.MaxLengthAttribute.IsValid(object value) ... System.ComponentModel.DataAnnotations.MaxLengthAttribute.IsValid(对象值)

... System.ComponentModel.DataAnnotations.ValidationAttribute.IsValid(object value, ValidationContext validationContext) ... System.ComponentModel.DataAnnotations.ValidationAttribute.IsValid(对象值,ValidationContext 验证上下文)

... System.ComponentModel.DataAnnotations.ValidationAttribute.GetValidationResult(object value, ValidationContext validationContext) ... System.ComponentModel.DataAnnotations.ValidationAttribute.GetValidationResult(对象值,ValidationContext 验证上下文)

Files文件

AppDbContext.cs AppDbContext.cs

Application Database Context应用程序数据库上下文

namespace KingsEye.Data
{
    public class AppDbContext : IdentityDbContext
    {
        public AppDbContext(DbContextOptions<AppDbContext> options) : base(options)  { }

        public DbSet<Home>       Home       { get; set; }
        public DbSet<Pages>      Pages      { get; set; }
        public DbSet<Newsletter> Newsletter { get; set; }
    }
}

CollectionModel.cs集合模型.cs

View Model used on index.cshtml and shared newsletter.cshtml view查看 index.cshtml 和共享 newsletter.cshtml 视图上使用的 Model

namespace KingsEye.Models
{
    public class CollectionModel
    {
        public Home       Home       { get; set; }
        public Pages      Pages      { get; set; }
        public Newsletter Newsletter { get; set; }
    }
}

Newsletter.cs时事通讯.cs

Newsletter View Model时事通讯查看 Model

namespace KingsEye.Models
{
    public class Newsletter
    {
        #region Newsletter
        [Display(Name = "Newsletter ID: ")]
        [Required(ErrorMessage = "Newsletter ID Required!")]
        public int     Id     { get; set; }

        [Display(Name = "Full Name: ")]
        [DataType(DataType.Text)]
        public string   Fname  { get; set; }

        [Display(Name = "E-Mail Address: ")]
        [DataType(DataType.EmailAddress)]
        public string   Email  { get; set; }

        [Display(Name = "Phone Number: ")]
        [DataType(DataType.PhoneNumber)]
        public int      Phone  { get; set; }

        [Display(Name = "Active: ")]
        [MaxLength(1)]
        public int      Active { get; set; }

        [Display(Name = "GUID: ")]
        [MaxLength(37)]
        public string   GUID { get; set; }

        [Display(Name = "Created: ")]
        [DataType(DataType.DateTime)]
        public DateTime Create { get; set; }

        [Display(Name = "Updated: ")]
        [DataType(DataType.DateTime)]
        public DateTime Update { get; set; }
        #endregion
    }
}

HomeController.cs家庭控制器.cs

Home Controller主页 Controller

[HttpPost]
public async Task<IActionResult> NewsletterSignup(CollectionModel model)
{ 
    <= Error: is prompting prior to the body of this method being called, 
              and the parameter object being populated with post data!!!

    var newsletter = new Newsletter
    {
        Id     = 0,
        Fname  = model.Newsletter.Fname,
        Email  = model.Newsletter.Email,
        Phone  = model.Newsletter.Phone,
        Active = 0,
        GUID   = Guid.NewGuid().ToString(),
        Create = DateTime.Now,
        Update = DateTime.Now
    };

    ...
}

_Newsletter.cshtml _Newsletter.cshtml

Shared view for the newsletter form通讯表单的共享视图

@model CollectionModel

<div id="newsletter">

    @if (User.Identity.IsAuthenticated)
    {
        <header>
            <i class="far fa-envelope-open"></i>
            <div class="text">Newsletter</div>
            <i class="far fa-envelope-open"></i>
        </header>

        <main>Subscribe to our newsletter</main>

        <footer>
            <form asp-controller="Home" asp-action="NewsletterSignup" method="post" id="newsletter-form" class="text-danger input-form">
                <div asp-validation-summary="ModelOnly"></div>

                <div class="form-group">
                    <input asp-for="@Model.Newsletter.Id" type="hidden" value="0" />
                </div>

                <div class="form-group">
                    <input asp-for="@Model.Newsletter.Fname" id="email-signed" class="form-control" placeholder="Your Name" />
                    <span asp-validation-for="@Model.Newsletter.Fname"></span>
                </div>

                <div class="form-group">
                    <input asp-for="@Model.Newsletter.Email" type="hidden" value="place@holder.com" />
                </div>

                <div class="form-group">
                    <input asp-for="@Model.Newsletter.Phone" id="email-signed" class="form-control" placeholder="(000) 000-0000" />
                    <span asp-validation-for="@Model.Newsletter.Phone"></span>
                </div>

                <div class="form-group input-submit">
                    <input id="newsletter-subscribe" type="submit" value="Subscribe" class="btn material-button" />
                </div>

                <div class="form-group">
                    <input asp-for="@Model.Newsletter.Active" type="hidden" value="0" />
                </div>

                <div class="form-group">
                    <input asp-for="@Model.Newsletter.GUID" type="hidden" value="0" />
                </div>

                <div class="form-group">
                    <input asp-for="@Model.Newsletter.Create" type="hidden" value="0" />
                </div>

                <div class="form-group">
                    <input asp-for="@Model.Newsletter.Update" type="hidden" value="0" />
                </div>

            </form>
        </footer>
    }
    else
    {
        <main>
            Please <a asp-controller="Auth" asp-action="Register">Sign-Up</a> to Subscribe for a Newsletter!
        </main>
    }
</div>

Goal目标

Would like to identify where this error is propagating from so that the exception in question can be debugged accordingly.想要确定此错误从何处传播,以便可以相应地调试有问题的异常。 Any advice or direction would surely be appreciated.任何建议或方向肯定会受到赞赏。

  • Thanks and cheers in advance.提前感谢和欢呼。

MaxLenght attribute is for a string MaxLenght 属性用于字符串

    [Display(Name = "Active: ")]
    [MaxLength(1)] // this will fail
    public int      Active { get; set; }

    [Display(Name = "GUID: ")] 
    [MaxLength(37)] //this is okay
    public string   GUID { get; set; }

https://docs.microsoft.com/en-us/dotnet/api/system.componentmodel.dataannotations.maxlengthattribute?view=netframework-4.8 https://docs.microsoft.com/en-us/dotnet/api/system.componentmodel.dataannotations.maxlengthattribute?view=netframework-4.8

Gets the maximum allowable length of the array or string data.获取数组或字符串数据的最大允许长度。

Maxlengh property is causing trouble in your code.You may dont face any issue while post,delete or get but while updating or editing error will pop out.just get rid of that property add migration and update database. Maxlengh 属性在您的代码中造成问题。您在发布、删除或获取时可能不会遇到任何问题,但在更新或编辑时会弹出错误。只需摆脱该属性添加迁移和更新数据库。

暂无
暂无

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

相关问题 错误:System.InvalidCastException:无法将“System.Byte”类型的对象转换为“System.Int32”类型 - Error: System.InvalidCastException: Unable to cast object of type 'System.Byte' to type 'System.Int32' InvalidCastException:无法将“System.Int32”类型的对象转换为“System.String”类型 - InvalidCastException: Unable to cast object of type 'System.Int32' to type 'System.String' InvalidCastException:无法将“System.String”类型的对象转换为“System.Int32”类型 - InvalidCastException: Unable to cast object of type 'System.String' to type 'System.Int32' Contoso 大学项目:InvalidCastException:无法将“System.String”类型的对象转换为“System.Int32”类型 - Contoso University Project: InvalidCastException: Unable to cast object of type 'System.String' to type 'System.Int32' System.InvalidCastException:无法将类型为“System.Linq.OrderedEnumerable`2[System.String,System.Int32]”的 object 转换为类型 [System.Int32]' - System.InvalidCastException : Unable to cast object of type 'System.Linq.OrderedEnumerable`2[System.String,System.Int32]' to type [System.Int32]' LINQ ToDictionary System.InvalidCastException:&#39;无法将类型为&#39;System.Int32&#39;的对象强制转换为类型为&#39;System.String&#39;。 - LINQ ToDictionary System.InvalidCastException: 'Unable to cast object of type 'System.Int32' to type 'System.String'.' 如何修复&#39;InvalidCastException:无法将类型为&#39;System.Int32&#39;的对象转换为类型为&#39;System.String&#39;的对象 - How can I fix the 'InvalidCastException: Unable to cast object of type 'System.Int32' to type 'System.String' System.InvalidCastException:无法将“System.Double”类型的 object 转换为代码中的“System.Int32”类型 - System.InvalidCastException: Unable to cast object of type 'System.Double' to type 'System.Int32' in code 类型&#39;&lt;&gt; f__AnonymousType2`2 [System.String,System.Int32]&#39;必须声明一个默认(无参数)构造函数 - The type '<>f__AnonymousType2`2[System.String,System.Int32]' must declare a default (parameterless) constructor System.Data.Entity.Infrastructure.DbRawSqlQuery`1 [System.Int32]&#39;键入“ System.IConvertible错误” - System.Data.Entity.Infrastructure.DbRawSqlQuery`1[System.Int32]' to type 'System.IConvertible Error
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM