Rasheen Ruwisha
Rasheen Ruwisha

Reputation: 155

Entity Framework Error Deleting Objects With Foreign Keys

I need to delete a contact that an event is already created with, the structure in how the data is saved is as follows

Events Table

enter image description here

Contacts Table

enter image description here

I have a separate table called EventContacts that manage the relationship between events and contacts

enter image description here

The class for Events

public class Events
    {

        [Key]
        public string id { get; set; }
        public string title{ get; set; }
        public string desc{ get; set; }
        public virtual List<Contact> contacts{ get; set; }
    }

Contacts class

public class Contact
    {
        public string ContactId { get; set; }  
        public string name{ get; set; }
        public string email{ get; set; }
    }

I remove the contacts using this code

using (var db= new DatabaseModel())
{
     Contact contact = db.Contacts.Find(id);
     db.Contact.Remove(contact);
     db.SaveChanges();
}

To add an event i use this

List<Contact> cons = new List<Contact>();
foreach (ComboItem cmb in cbItems)
{
   EventContact evntConts = new EventContact()
   {
      contId = cmb.contId,
      evntId = eventidevntId
      userId = userId,
    };

    cons.Add(evntConts);
}
UserEvent events = new UserEvent()
{
   eventid= this.evntid,
   title= txt_title.Text,
   description = txt_des.Text,
   evcontacts = cons
};



using (var db= new DatabaseModel())
{
   db.Evnts.Add(evnt);
   db.SaveChanges();
}

This code works fine if there are no events that are created with that user, but if I add the user to an event and then remove the user this does not work. How can I fix that?

Upvotes: 0

Views: 63

Answers (1)

siri
siri

Reputation: 114

If there is a Foreign Key and you have record - it needs to be deleted first (the operation on Event-contacts needs to be first) and then try removing Contacts.

using (var db= new DatabaseModel())
{
     Contact contact = db.Contacts.Find(id);
     if(contact != null){
     EventContact eventContact = db.EventContacts.Where(x=>x.contactId == 
        contact.Id).ToList();
      foreach(var item in eventVContact){
        db.contact.Remove(item);
        db.SaveChanges();
       }
     }
     if(eventContact?.Any()??true){
      db.Contact.Remove(contact);
      db.SaveChanges();
     }

}

Upvotes: 1

Related Questions