【发布时间】:2016-08-08 06:11:32
【问题描述】:
我们在尝试将所有数据写入数据库时遇到问题。我们正在使用实体框架代码优先方法和 SQL Server。我们的连接已准备就绪,我们的表已创建。
我们现在将数据保存到 List 中。但我们无法将其发送到数据库。它是我们的代码。当代码到达 Save.Changes 行时,它会崩溃
这是错误代码
类型异常 'System.Data.Entity.Infrastructure.DbUpdateException' 发生在 EntityFramework.dll 但未在用户代码中处理
附加信息:更新条目时出错。 有关详细信息,请参阅内部异常。
联系实体
public class Contact
{
[Key]
public int Id { get; set; }
public string cn { get; set; }
public string sn { get; set; }
public string c { get; set; }
public string l { get; set; }
public string st{ get; set; }
public string title{ get; set; }
public string postalCode { get; set; }
public string physicalDeliveryOfficeName{ get; set; }
public long? telephoneNumber{ get; set; }
public string givenName{ get; set; }
public string initials { get; set; }
public DateTime? whenCreated { get; set; }
public DateTime? whenChanged { get; set; }
public string co{ get; set; }
public string displayName{ get; set; }
public int? delivContLength { get; set; }
public string company{ get; set; }
public string proxyAdress{ get; set; }
public string streetAdress{ get; set; }
public string mailNickname{ get; set; }
public string name{ get; set; }
public int? primaryGroupID { get; set; }
public string objectGUID { get; set; }
public string objectSID{ get; set; }
public string sAMAccountName{ get; set; }
public string mail{ get; set; }
public string homePhone { get; set; }
public string mobile { get; set; }
}
实体框架页面
namespace WebApplication5.EntityFramework
{
public class PhoneDexContext : DbContext
{
public DbSet<Contact> Contacts { get; set; }
public DbSet<SyncInfo> SyncInfo { get; set; }
}
}
数据库部分
namespace WebApplication5.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
var test = new LdapServiceManager().getAllUsers();
var phoneDex = new PhoneDexContext();
foreach (var contact in test)
{
//phoneDex.Entry(contact).State = System.Data.Entity.EntityState.Added;
phoneDex.Contacts.Add(contact);
//TODO HATA ALINIYOR
phoneDex.SaveChanges();
}
return View();
}
}
}
【问题讨论】:
-
它会抛出什么异常?当您遇到错误时,请始终显示错误消息和堆栈跟踪 - 它有 99% 的问题的答案。
-
对不起,我忘记了 EntityFramework.dll 中出现“System.Data.Entity.Infrastructure.DbUpdateException”类型的异常,但未在用户代码中处理其他信息:更新条目时出错。有关详细信息,请参阅内部异常。
-
还有一个InnerException,把它的内容也贴出来。
-
内部异常是什么??
-
.NET
Exception对象具有InnerException类型的Exception属性。因此,如果您的异常是由于另一个异常而生成的,或者依赖于它,您可以将其存储在那里以更好地描述问题。实际上,可以有一个很长的InnerExceptions 链。对于EntityFramework,大多数错误位于InnerException对象中。只需使用此属性即可访问它:catch (Exception e) { Console.WriteLine(e.InnerException); }
标签: c# sql-server entity-framework