There is a way to do both kinds, which Matthew described in one step. This requires a slight change to your model — you need to add a foreign key to the Phone object and create a composite key containing both PhoneId and ContactId .
This makes an instance of the Phone class bound to an instance of the Contact class. With these settings, when you remove the phone from the contact someContact.Phones.Remove(somePhone); , EF removes the phone from the database, because it knows that the phone cannot exist without connecting to this particular contact.
Model:
public class Contact { public int ContactId { get; set; } public virtual ICollection<Phone> Phones { get; set; } } public class Phone { public int PhoneId { get; set; } public int ContactId { get; set; } public string PhoneNumber { get; set; } }
Configuration:
modelBuilder.Entity<Contact>() .HasMany(o => o.Phones) .WithRequired() .HasForeignKey(f => f.ContactId) .WillCascadeOnDelete(true); modelBuilder.Entity<Phone>() .HasKey(o => new { o.PhoneId, o.ContactId });
Lukas Kabrt
source share