错误Guid应包含32个数字,包含4个破折号

时间:2018-06-16 11:10:37

标签: c# asp.net postgresql entity-framework-core guid

出错了

“Guid应包含32位数字,包含4个破折号(xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx)”

GUID输入为“68f0eaed-189e-4c65-8cf8-475539d6f21b”

    context.Countries.AddRange(GetCountryData(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "csv", "country.csv")));

    await context.SaveChangesAsync();


    public List<Data.Country> GetCountryData(string filePath)
    {
        string csvRead = File.ReadAllText(filePath);
        string[] csvFileRecord = csvRead.Split('\n');
        List<Data.Country> dataRecordList = new List<Data.Country>();

        foreach (var row in csvFileRecord.Skip(1))
        {
            if (!string.IsNullOrEmpty(row))
            {
                var cells = row.Split(',');
                var dataRecord = new Data.Country
                {
                    Id = Guid.Parse(cells[0]),
                    Code = cells[1],
                    Name = cells[2]
                };
                dataRecordList.Add(dataRecord);
            }
        }

        return dataRecordList;
    }

CSV文件

"id","code","name"
"68f0eaed-189e-4c65-8cf8-475539d6f21b","AX","Åland Islands"
"76cf600f-7bf6-40fb-8803-142eac60f3dd","AL","Albania"
...

已编辑更新了代码,现在获取了正确的GUID值,但仍然出现错误

My input "68f0eaed-189e-4c65-8cf8-475539d6f21b"

fail: MyApp.ContextSeed[0]
      Guid should contain 32 digits with 4 dashes (xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx).
info: Microsoft.EntityFrameworkCore.Database.Command[20101]
      Executed DbCommand (1ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
      SELECT CASE
          WHEN EXISTS (
              SELECT 1
              FROM public.country AS c)
          THEN TRUE::bool ELSE FALSE::bool
      END

1 个答案:

答案 0 :(得分:1)

我建议将代码更改为以下内容:

public List<Data.Country> GetCountryData(string filePath)
    {
        string csvRead = File.ReadAllText(filePath);
        string[] csvFileRecord = csvRead.Split('\n');
        List<Data.Country> dataRecordList = new List<Data.Country>();

        foreach (var row in csvFileRecord.Skip(1))
        {
            if (!string.IsNullOrEmpty(row))
            {
                var cells = row.Split(',');
                var dataRecord = new Data.Country
                {
                    Id = Guid.Parse(cells[0].Replace("\"", "")),
                    Code = cells[1].Replace("\"", ""),
                    Name = cells[2].Replace("\"", "")
                };
                dataRecordList.Add(dataRecord);
            }
        }

        return dataRecordList;
    }

根据您刚添加的信息,很明显您正在尝试将字符串(不是Guid)转换为Guid。请注意cells处的新索引。 csvFileRecord.Skip(1);也没有跳过任何内容;现在它应该有效,因为在IEnumerable的头部返回了一个新的foreach。 另请注意,您需要从"中删除cells个字符!