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

Error Guid should contain 32 digits with 4 dashes

遇到错误

"Guid should contain 32 digits with 4 dashes (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

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

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); 也没有跳过任何东西;现在它应该可以工作了,因为在 foreach 的头部返回了一个新的 IEnumerable。 另请注意,您需要从 cells!

中删除 " 个字符