【问题标题】:Import Data from Excel to SQL Server DB using LINQ to Excel使用 LINQ to Excel 将数据从 Excel 导入 SQL Server DB
【发布时间】:2014-11-07 17:20:53
【问题描述】:

我是 Linq to SQL 的新手,我想将 Excel 文件内容导入我的 SQL 服务器数据库。

这是我的代码:

private void btnImport_Click(object sender, RoutedEventArgs e)
    {
        dbEntities = new BASUEntities();
        string pathToExcelFile = importFileName;
        var excelFile = new ExcelQueryFactory(pathToExcelFile);

        excelFile.AddMapping<UserInfo>(x => x.FirstName, "FName");
        excelFile.AddMapping<UserInfo>(x => x.LastName, "LName");
        excelFile.AddMapping<UserInfo>(x => x.NationalCode, "NatCode");
        excelFile.AddMapping<UserInfo>(x => x.EmploymentID, "EmpID");
        excelFile.AddMapping<UserInfo>(x => x.WorkUnit, "WorkUnit");
        excelFile.AddMapping<UserInfo>(x => x.JobOrdination, "JobOrd");
        excelFile.AddMapping<UserInfo>(x => x.Profession, "Profession");
        excelFile.AddMapping<UserInfo>(x => x.PostTitle, "PTitle");
        excelFile.AddMapping<UserInfo>(x => x.EmploymentType, "EmpType");
        excelFile.AddMapping<UserInfo>(x => x.PhoneNumber, "PhoneNo");

        excelFile.TrimSpaces = TrimSpacesType.Both;
        excelFile.ReadOnly = true;

        IQueryable<UserInfo> UserInfz = (from a in excelFile.Worksheet<UserInfo>()
            select a);

        foreach (UserInfo userInfo in UserInfz)
        {
            dbEntities.UserInfoes.Add(userInfo);
            dbEntities.SaveChanges();
        }
        LoadAllUsers(); //Load Users in DataGrid

    }

它工作了 55 行,然后我得到了这个错误:

类型的第一次机会异常 'System.Data.Entity.Validation.DbEntityValidationException' 发生 在 EntityFramework.dll 中

附加信息:一个或多个实体的验证失败。 有关详细信息,请参阅“EntityValidationErrors”属性。

我的 excel 文件包含 700 多行。 我认为这是一个内存问题!

我该如何解决这个问题?

【问题讨论】:

  • 验证错误信息是什么?我很确定第 56 行有问题。有些东西不适合模型验证
  • @Aniket 我尝试从 excel 中删除第 56 行,它继续到 200 但卡在那里,并且删除行不再有用......它只是导入 200 行 excel。
  • afaik,数据似乎已损坏。打开无法比较的东西,看看哪一行是允许的,哪一行是失败的。

标签: c# sql excel linq entity-framework


【解决方案1】:

第 56 行和第 200 行生成验证错误,因为这些行中的数据与 UserInfo 的定义不匹配

以下代码将准确告诉您这些行的问题是什么

foreach (UserInfo userInfo in UserInfz)
{
    dbEntities.UserInfoes.Add(userInfo);
    dbEntities.SaveChanges();
}
catch (DbEntityValidationException ex)
{
    StringBuilder sb = new StringBuilder();
    foreach (var eve in ex.EntityValidationErrors)
    {
        sb.AppendLine(String.Format("Entity of type '{0}' in state '{1}' has the following validation errors:", eve.Entry.Entity.GetType().Name, eve.Entry.State));
        foreach (var ve in eve.ValidationErrors)
        {
            sb.AppendLine(String.Format("- Property: '{0}', Error: '{1}'", ve.PropertyName, ve.ErrorMessage));
        }
    }
    throw new Exception(sb.ToString(), ex);
}

【讨论】:

    猜你喜欢
    • 2015-01-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多