实体框架,向数据库添加数据

时间:2016-08-08 06:11:32

标签: c# sql-server entity-framework

当我们将所有数据都尝试到数据库时,我们遇到了问题。我们正在使用Entity Framework Code First方法和SQL Server。我们的连接准备就绪,我们的表已经创建。

我们现在将数据保存到列表中。但我们无法将其发送到数据库。它是我们的代码。当代码进入Save.Changes行时,它会破坏

其错误代码

  

类型的例外   ' System.Data.Entity.Infrastructure.DbUpdateException'发生在   EntityFramework.dll但未在用户代码中处理

     

其他信息:更新条目时发生错误。   有关详细信息,请参阅内部异常。

联系ENTITY

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; }
}

ENTITY FRAMEWORK PAGE

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();
        }    
    }
}

1 个答案:

答案 0 :(得分:1)

已经做完了,谢谢。

它是关于我们没有创建的另一个数据库。我们使用的是localhost数据库的连接字符串,但还有另一个是由模板创建的。删除模板的数据库后,它解决了:)

相关问题