问题描述
我已连接到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; }
}
}
解决方法
您正在将StringLength
属性设置为Nullable<int>
类型的属性。因此,它尝试将int强制转换为string。您可能打算将属性放在 CountryName 属性中,如下所示:
[StringLength(50)]
public string CountryName { get; set; }
public Nullable<int> ContinentID { get; set; }
,
[StringLength(50)]
public Nullable<int> ContinentID { get; set; }
在这里,您告诉EntityFramework预期的字符串为50,而数据类型为Nullable<int>
。
注释应该在它们“描述”的属性之上,而不是下面,因为这50个限制似乎适用于CountryName而不是ContinentID?
,如果您想限制字符串字段,则应在该字段上添加数据注释
[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; }
,
您可以用[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; }
...