首页 > 解决方案 > 错误 Guid 应包含 32 位数字和 4 个破折号

问题描述

出错了

“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

标签: c#asp.netpostgresqlentity-framework-coreguid

解决方案


I suggest to change the code to the following:

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

With the information you just added, it is clear that you are trying to convert a string, that is not a Guid, to a Guid. Note the new indexes at cells. Also csvFileRecord.Skip(1); didn't skip anything; now it should work, because a new IEnumerable is returned in the foreach's head. Also note that you will need to remove the " characters from the cells!


推荐阅读