Linq to entities EntityFramework.Core.dll中发生System.InvalidCastException异常

Linq to entities EntityFramework.Core.dll中发生System.InvalidCastException异常,linq-to-entities,entity-framework-core,asp.net-core,Linq To Entities,Entity Framework Core,Asp.net Core,以下是应用程序实体: 公共类应用程序 { [关键] [列(TypeName=“integer”)] public int ApplicationID{get;set;} [必需] [列(TypeName=“nvarchar(50)”)] 公共字符串ApplicationName{get;set;} [列(TypeName=“nvarchar(150)”)] 公共字符串说明{get;set;} [必需] [外键(“mTechnology”)] [列(TypeName=“integer”)] pub

以下是
应用程序实体

公共类应用程序
{
[关键]
[列(TypeName=“integer”)]
public int ApplicationID{get;set;}
[必需]
[列(TypeName=“nvarchar(50)”)]
公共字符串ApplicationName{get;set;}
[列(TypeName=“nvarchar(150)”)]
公共字符串说明{get;set;}
[必需]
[外键(“mTechnology”)]
[列(TypeName=“integer”)]
public int TechnologyID{get;set;}
[必需]
[列(TypeName=“int”)]
通过{get;set;}创建的公共字符串
[必需]
[列(TypeName=“datetime”)]
公共日期时间CreatedDate{get;set;}
公共虚拟技术{get;set;}
}
在执行下面的LINQ查询时,我在
foreach循环的
run-time
中得到一个错误

List technologyList=new List();
var query=来自_mApplicationDbContext.Applications中的
a组技术由a组技术分为g组
选择新的
{
技术ID=g.键
};
foreach(查询中的var项)
{
technologyList.Add(item.TechnologyID);
}
以下是错误消息:

中发生“System.InvalidCastException”类型的异常 EntityFramework.Core.dll,但未在用户代码中处理

其他信息:无法强制转换“System.Int32”类型的对象 键入“System.String”


LINQ查询是错误的还是其他错误?

从您在模型中犯的错误来看

当您将外键技术ID定义为整数时,试图使用无效的数据类型。不知道您使用的是哪种类型的数据库,我假设您使用的是某种风格的sql server,在这种情况下,数据类型“integer”不存在

贝娄应该解决这个问题:

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; }
}

作为补充说明,您并不总是需要为所有属性指定typename。如果您有一个int属性,并且要将其映射到int列,则只需使用[column]属性,EF将使用正确的int类型。当您试图在模型中使用long而sql server中没有long时,指定类型名更为重要,因此您可以将TypeName属性用作[Column(TypeName=“bigint”)]

谢谢!对于解决方案和旁注。