{“从实例化的'System.Guid'类型到'System.Int32'类型的指定强制转换无效

本文关键字:类型 System 转换 无效 Int32 实例化 Guid 从实例化的 | 更新日期: 2023-09-27 17:56:54

>我有一个实体框架模型,其中包含一个资产表,如下所示:

public partial class Asset
{
    public int Switch { get; set; }
    public string Port { get; set; }
    public string Name { get; set; }
    public string Connection { get; set; }
    public string Interface { get; set; }
    public string ConnectionUser { get; set; }
    public string ConnectionDate { get; set; }
}

我试图只返回"名称"列。这是我用来执行此操作的代码:

    // create the entity model for DB operations
    acls3Entities entities = new acls3Entities();
    List<Asset> assets = entities.Assets.ToList();
    foreach (Asset asset in assets)
    {
        Console.WriteLine(string.Format("{0}", asset.Name));
    };

但是,它给了我这篇文章标题中定义"资产"的行中引用的错误。如何解决此问题?

{“从实例化的'System.Guid'类型到'System.Int32'类型的指定强制转换无效

GUID 不是 int,在您的数据库中,Switch 是一个 GUID。

GUID 是由 - 划分的十六进制数

下面是 GUID 的三个示例:

839E4FB1-F5F5-4C46-AFD1-000002CC625F

06F6D8BA-C10D-4806-B190-000006BA0513

2D3343FD-3E8A-4B33-9198-00002031F5F8

int 不能包含字母,也不能包含 -

所以你的资产更像是:

public partial class Asset
{
public Guid Switch { get; set; }  // here <- GUID
public string Port { get; set; }
public string Name { get; set; }
public string Connection { get; set; }
public string Interface { get; set; }
public string ConnectionUser { get; set; }
public string ConnectionDate { get; set; }
}

还要确保您的 edmx 文件始终是最新的,这是您在遇到实体错误时应该检查的内容。

为此:

  1. 在您的项目中查找您的 .edmx 文件(您的文件可能称为 acls3Entities.edmx)

  2. 删除该页面内的所有内容...好像有点冷?在执行此操作之前复制您的项目,这样您就可以进行备份。

  3. 右键单击白色空白中的某个地方,然后选择Update from database或看起来像这样的东西(我的视觉工作室不是英语......

  4. 选择您需要的每个表/视图/存储过程,仅此而已

I solved this problem by using查询条件两端的ToString()函数。

初始问题:

Guid userId = Guid.Parse(User.Identity.GetUserId());    
candidateDashBoard.DismissalRecord = db.DismissalRecords.Where(c => 
                  c.CandidateId == userId).FirstOrDefault();

溶液:

Guid userId = Guid.Parse(User.Identity.GetUserId());
candidateDashBoard.DismissalRecord = db.DismissalRecords.Where(c => 
                  c.CandidateId.ToString() == userId.ToString()).FirstOrDefault();
相关文章: