c# - 使用 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; }
}
}
解决方案
You are setting the StringLength
attribute to a property of type Nullable<int>
. Hence, it tries to cast the int to string. You probably intended to put the attribute to the CountryName property as follows:
[StringLength(50)]
public string CountryName { get; set; }
public Nullable<int> ContinentID { get; set; }
推荐阅读
- python - 如何在嵌套的for循环中解析来自两个具有相似键和不同值的api调用的json响应
- javascript - 递归 HTTP 调用 - 从回调管道解析数据
- reinforcement-learning - 这是真的 ?预期 SARSA 和双 Q-Learning 怎么样?
- python - 获取OpenCV中多个小轮廓的外轮廓
- r - 在 R 中读取 xlsx 文件时如何使用错误处理?
- javascript - 在 Node.js 上运行多个物理世界,而不是充分利用服务器
- liferay - 继承的站点角色 - Liferay 7
- reactjs - Eslint:jsx上的“意外令牌/”
- reactjs - 未找到模块(Typescript 和 baseUrl 选项)
- assembly - Mips 汇编程序中执行的指令总数(instr.counter vs instr.stats)