以下是应用程序实体
:
public class Application
{
[Key]
[Column(TypeName = "integer")]
public int ApplicationID { get; set; }
[Required]
[Column(TypeName = "nvarchar(50)")]
public string ApplicationName { get; set; }
[Column(TypeName = "nvarchar(150)")]
public string Description { get; set; }
[Required]
[ForeignKey("mTechnology")]
[Column(TypeName = "integer")]
public int TechnologyID { get; set; }
[Required]
[Column(TypeName = "int")]
public string CreatedBy { get; set; }
[Required]
[Column(TypeName = "datetime")]
public DateTime CreatedDate { get; set; }
public virtual mTechnology Technology { get; set; }
}
在执行以下 LINQ 查询时,我在 foreach 循环
的 run-time
处收到错误
List<int> technologyList = new List<int>();
var query = from a in _mApplicationDbContext.Applications
group a.Technology by a.TechnologyID into g
select new
{
TechnologyID = g.Key
};
foreach (var item in query)
{
technologyList.Add(item.TechnologyID);
}
错误信息如下:
An exception of type 'System.InvalidCastException' occurred in EntityFramework.Core.dll but was not handled in user code
Additional information: Unable to cast object of type 'System.Int32' to type 'System.String'.
LINQ 查询是否错误或有其他错误?
最佳答案
从表面上看,你在模型中犯了一个错误。
当您将外键 TechnologyID 定义为整数时,您尝试使用无效的数据类型。在不知道您正在使用什么类型的数据库的情况下,我假设您正在使用某种风格的 SQL Server,在这种情况下,数据类型“整数”不存在。
波纹管应该可以解决该问题:
public class Application
{
[Key]
[Column]
public int ApplicationID { get; set; }
[Required]
[Column(TypeName = "nvarchar(50)")]
public string ApplicationName { get; set; }
[Column(TypeName = "nvarchar(150)")]
public string Description { get; set; }
[Required]
[ForeignKey("mTechnology")]
[Column]
public int TechnologyID { get; set; }
[Required]
[Column(TypeName = "int")]
public string CreatedBy { get; set; }
[Required]
[Column]
public DateTime CreatedDate { get; set; }
public virtual mTechnology Technology { get; set; }
}
顺便说一句,您并不总是需要为所有属性指定类型名称。如果您有 int 属性并将其映射到 int 列,则只需使用 [Column] 属性,EF 将使用正确的 int 类型。当您尝试在模型中使用 long 且 sql server 中没有 long 时,指定类型名称更为重要,因此您可以使用 TypeName 属性作为 [Column(TypeName = "bigint")]
关于linq-to-entities - EntityFramework.Core.dll 中发生 System.InvalidCastException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34927042/