我是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行,然后我收到了这个错误:
类型的第一次机会异常 &#39; System.Data.Entity.Validation.DbEntityValidationException&#39;发生了 在EntityFramework.dll
中其他信息:一个或多个实体的验证失败。 请参阅&#39; EntityValidationErrors&#39;物业详情。
我的Excel文件包含700多行。 我认为这是一个记忆问题!
我该如何解决这个问题?
答案 0 :(得分:0)
第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);
}