实体框架插入新行而不是更新它们

jur*_*pro 4 c# asp.net entity-framework asp.net-mvc-4

我将数据更新到数据库时遇到问题.当我想更新数据时,Entitiy Framework会向可以有多行的表(具有外键的表)添加新行.

数据库模型:

数据库模型

当我更新电话/联系人或标签实体时,实体框架会自动添加新行而不是更新它

这是我使用的代码:

public string UpdateContact(Contact contact)
{
    if (contact != null)
    {

        int id = Convert.ToInt32(contact.id);
        Contact Updatecontact = db.Contacts.Where(a => a.id == id).FirstOrDefault();
        Updatecontact.firstname = contact.firstname;
        Updatecontact.lastname = contact.lastname;
        Updatecontact.address = contact.address;
        Updatecontact.bookmarked = contact.bookmarked;
        Updatecontact.city = contact.city;
        Updatecontact.notes = contact.notes;
        Updatecontact.Emails1 = contact.Emails1;
        Updatecontact.Phones1 = contact.Phones1;
        Updatecontact.Tags1 = contact.Tags1;
        db.SaveChanges();
        return "Contact Updated";

    }
    else
    {
        return "Invalid Record";
    }
}
Run Code Online (Sandbox Code Playgroud)

编辑:

这是EF模型代码:

联系:

public partial class Contact
{
    public Contact()
    {
        this.Emails1 = new HashSet<Email>();
        this.Phones1 = new HashSet<Phone>();
        this.Tags1 = new HashSet<Tag>();
    }

    public int id { get; set; }
    public string firstname { get; set; }
    public string lastname { get; set; }
    public string address { get; set; }
    public string city { get; set; }
    public Nullable<byte> bookmarked { get; set; }
    public string notes { get; set; }

    public virtual ICollection<Email> Emails1 { get; set; }
    public virtual ICollection<Phone> Phones1 { get; set; }
    public virtual ICollection<Tag> Tags1 { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

电子邮件/标签和电话具有相同的型号(值的名称不同)

public partial class Email
{
        public int id { get; set; }
        public int id_contact { get; set; }
        public string email1 { get; set; }

        public virtual Contact Contact1 { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

Wik*_*hla 5

更新属性而不是设置新对象.

  Updatecontact.Emails1.email1 = contact.Emails1.email1;
  Updatecontact.Phones1.number = contact.Phones1.number;
  Updatecontact.Tags1.tag1 = contact.Tags1.tag1;
Run Code Online (Sandbox Code Playgroud)

编辑:您的联系人模型似乎包含电子邮件,电话和标签列表.如果是这样,那么简单的分配将不起作用.相反,当从客户端发送时,您必须逐个查找并更新:

 foreach ( var email in contact.Emails1 )
 {
     // first make sure the object is retrieved from the database 
     var updateemail = Updatecontact.Emails1.FirstOrDefault( e => e.id == email.id );
     // then update its properties
     updateemail.email1 = email.email1;
 }

 // do the same for phones and tags
Run Code Online (Sandbox Code Playgroud)