【问题标题】:{"The specified cast from a materialized 'System.Guid' type to the 'System.Int32' type is not valid."{“从物化 'System.Guid' 类型到 'System.Int32' 类型的指定转换无效。”
【发布时间】:2016-07-14 15:12:37
【问题描述】:

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

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

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

【问题讨论】:

  • 查看数据库中 Switch 列的类型,如果是 GUID,则将其更改为 int。

标签: c# asp.net entity-framework


【解决方案1】:

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. 选择您需要的每个表/视图/存储过程,仅此而已

【讨论】:

  • 刚刚尝试了上面的答案并得到以下错误:附加信息:概念侧类型'acls3Model.Asset'中成员'Switch'的类型'Edm.Int32'不匹配对象侧类型上成员“Switch”的类型“System.Guid”
  • Hem...也许只是更新您的 edmx 文件...如果您知道如何...如果不是我可以解释
【解决方案2】:

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

最初的问题:

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();

【讨论】:

  • 有同样的问题。知道为什么吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-02-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多