使用mvc的实体框架-数据注释

时间:2020-09-14 11:18:00

标签: c# asp.net-mvc entity-framework model-view-controller visual-studio-2019

我已连接到SQL数据库表,并且试图在模型的文件夹中为字符串CountryName创建数据注释。在网上给我一个错误:

System.InvalidCastException:无法将类型为“ System.Int32”的对象转换为类型为“ System.String”。

namespace WorldEventsWeb.Models
{
    using System;
    using System.Collections.Generic;
    using System.ComponentModel.DataAnnotations;

    public partial class tblCountry
    {
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
        public tblCountry()
        {
            this.tblEvents = new HashSet<tblEvent>();
        }
    
        public int CountryID { get; set; }
        public string CountryName { get; set; }
        [StringLength(50)]
        public Nullable<int> ContinentID { get; set; }
    
        public virtual tblContinent tblContinent { get; set; }
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
        public virtual ICollection<tblEvent> tblEvents { get; set; }
    }
}

4 个答案:

答案 0 :(得分:1)

您正在将StringLength属性设置为Nullable<int>类型的属性。因此,它尝试将int强制转换为string。您可能打算将属性放在 CountryName 属性中,如下所示:

[StringLength(50)]
public string CountryName { get; set; }

public Nullable<int> ContinentID { get; set; }

答案 1 :(得分:0)

[StringLength(50)]
public Nullable<int> ContinentID { get; set; }

在这里,您告诉EntityFramework预期的字符串为50,而数据类型为Nullable<int>

注释应该在它们“描述”的属性之上,而不是下面,因为这50个限制似乎适用于CountryName而不是ContinentID?

答案 2 :(得分:0)

如果您想限制字符串字段,则应在该字段上添加数据注释

[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
        public tblCountry()
        {
            this.tblEvents = new HashSet<tblEvent>();
        }
    
        public int CountryID { get; set; }
        [StringLength(50)]
        public string CountryName { get; set; }
        public Nullable<int> ContinentID { get; set; }
    
        public virtual tblContinent tblContinent { get; set; }
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
        public virtual ICollection<tblEvent> tblEvents { get; set; }

答案 3 :(得分:0)

您可以用[StringLength(50)]装饰Nullable属性ContentID,这仅适用于字符串。

数据注释在属性之后起作用,因此您只需将[StringLength(50)]注释移高2行

...

public int CountryID { get; set; }
[StringLength(50)]
public string CountryName { get; set; }
public Nullable<int> ContinentID { get; set; }

...