如何解决使用mvc的实体框架-数据注释
我已连接到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; }
...
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。