One-to-Many One-Way Relationships with First Code

I have a one-way unidirectional communication between a contact and a phone, defined as follows:

class Contact { int ContactId {get; set} ICollection<Phone> Phones {get; set} } class Phone { int PhoneId {get; set;} string PhoneNumber {get; set;} } 

Now at the domain level I am trying to do the following:

 someContact.Phones.Remove(somePhone); 

and when I try to call context.SaveChanges() , I get an exception because the relationship is defined as mandatory (for example, the phone cannot exist without contact). How can I solve this problem without using a foreign key or navigation property on the phone and without calling DbSet<Phone>.Remove(Phone) before calling SaveChanges() ?

+7
source share
2 answers

Basically, you answered your question, because the two things you described are separate:

  • Untie an object
  • Delete object

There might be a smart way for EF, but others asked the same question and got the answer you referred to:

eg. EF 4.1: Removing a child from a collection does not delete it - why?

+1
source

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 }); 
0
source

All Articles