c# - 错误 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
解决方案
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
!
推荐阅读
- java - 在 Android 画布上设置屏幕范围
- sequelize.js - Sequelize 数据检索向上
- option - 用于切换 TMUX 窗口的“ALT”键映射在 Mac Book 上不起作用
- symfony - Symfony 5.2 验证 json_login 请求
- mongodb - 将字符串附加到 MongoDB 中数组字段中的所有值
- mybatis - mybatis 支持检查属性是否存在?
- html - 嵌入在对象标签中的 txt 文件在应用程序运行时会出现编码错误?
- bash - AWK 找到一种方法来打印包含逗号分隔字符串中的单词的行
- javascript - 如何获取用户正在玩的游戏?不和谐.js
- input - 我怎样才能打破循环?真时: