[英]Entity Framework using mvc - data annotation
我已連接到 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; }
...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.