Reputation: 155
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
Contacts Table
I have a separate table called EventContacts that manage the relationship between events and contacts
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
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