使用LINQ to Excel将数据从Excel导入到SQL Server数据库
林新手在LINQ到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行工作,然后我得到这个错误:
在EntityFramework.dll中发生第一次机会“System.Data.Entity.Validation.DbEntityValidationException”typesexception
附加信息:一个或多个实体的validation失败。 有关更多详细信息,请参阅“EntityValidationErrors”属性。
我的Excel文件包含700多行。 我认为这是一个内存问题!
我如何解决这个问题?
行56和200生成validation错误,因为这些行中的数据与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); }