使用标识行将CSV写入数据表

时间:2019-10-28 18:28:53

标签: csvhelper

我具有以下设计的SQL Server数据库表:

    [Id]           INT            IDENTITY (1, 1) NOT NULL,
    [State]        NVARCHAR (MAX) NOT NULL,
    [Abbreviation] NVARCHAR (MAX) NOT NULL,
    CONSTRAINT [PK_USStates] PRIMARY KEY CLUSTERED ([Id] ASC)

我有一个.csv文件,格式如下:

Alabama, AL
Alaska, AK

注意:.csv文件中没有ID字段。

当我尝试将.csv文件导入到我的SQL Server数据库中时,我收到一条错误消息,因为它试图将“ Alabama”(。csv的字段1)写入ID字段(数据库表中的字段1)

我如何告诉CSVHelper数据库中的字段1是一个Identity字段,并忽略它,从而在字段2中写入“阿拉巴马州”,在字段3中写入“ AL”?

预先感谢您的帮助。

附录: 我正在使用Web表单导入。这里也可能会出现错误,因为这是我第一次尝试对这种代码进行编码...

public async Task<IActionResult> OnPostAsync()
        {

            using (var reader = new StreamReader(@"\\SomeComputer\SomePath\states.csv"))
            using (var csv = new CsvReader(reader))
            {
                csv.Configuration.HasHeaderRecord = false;

                IEnumerable<USStates> records = csv.GetRecords<USStates>();
                foreach (var record in records)
                {
                    _context.USStates.Add(record);
                    await _context.SaveChangesAsync();
                }
            }

            return RedirectToPage("./Index");

        }


Note: Sample states.csv data:


"Alaska","AK"
"American Samoa","AS"
"Arizona","AZ"
"Arkansas","AR"
"California","CA"
"Colorado","CO"
"Connecticut","CT"
"Delaware","DE"
"District Of Columbia","DC"
"Florida","FL"
"Georgia","GA"
"Guam","GU"
"Hawaii","HI"
"Idaho","ID"
"Illinois","IL"
"Indiana","IN"

1 个答案:

答案 0 :(得分:0)

您可以使用ClassMap来指示要查找的列以及在何处查找。

public async Task<IActionResult> OnPostAsync()
{
    using (var reader = new StreamReader(@"\\SomeComputer\SomePath\states.csv"))
    using (var csv = new CsvReader(reader))
    {
        csv.Configuration.HasHeaderRecord = false;
        csv.Configuration.RegisterClassMap<USStatesMap>();

        IEnumerable<USStates> records = csv.GetRecords<USStates>();
        foreach (var record in records)
        {
            _context.USStates.Add(record);
            await _context.SaveChangesAsync();
        }
    }
}

public class USStates
{
    public int Id { get; set; }
    public string State { get; set; }
    public string Abbreviation { get; set; }
}

public class USStatesMap : ClassMap<USStates>
{
    public USStatesMap()
    {
        Map(m => m.State).Index(0);
        Map(m => m.Abbreviation).Index(1);
    }
}