jureispro jureispro - 3 months ago 16
ASP.NET (C#) Question

Entity Framework inserting new rows instead of updating them

I have a problem when I am updating data to database. When I want to update data, Entitiy Framework adds new rows to tables that can have multiple rows (tables that have foreign key).

Database model:

Database model

When I update Phone/Contact or Tags entity, Entity Framework automatically adds new row instead of updating it

Here is code that I used:

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


EDIT:

Here is EF Model code:

Contact:

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


Emails/Tags and Phone have same model (with different name for value)

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

Answer

Update properties rather than set new objects.

  Updatecontact.Emails1.email1 = contact.Emails1.email1;
  Updatecontact.Phones1.number = contact.Phones1.number;
  Updatecontact.Tags1.tag1 = contact.Tags1.tag1;

Edit: seems that your contact model has lists of emails, phones and tags. If this is so, then simple assignment won't work. Instead, when sent from the client, you have to find one-by-one and update:

 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
Comments