Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Uni-directional one-to-many relationship with Code First

I have a one-to-many uni-directional relationship between Contact and Phone defined like this:

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

Now in the domain layer, i try 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 Required (eg. a phone cannot exist without a contact).
How can i solve this without using a foreign key or a navigation property in Phone and without the need to call DbSet<Phone>.Remove(Phone) before calling SaveChanges() ?

like image 842
Ibrahim Najjar Avatar asked Dec 19 '12 15:12

Ibrahim Najjar


People also ask

What is many-to-many relationships in code first approach?

A many-to-many relationship is defined in code by the inclusion of collection properties in each of the entities - The Categories property in the Book class, and the Books property in the Category class: public class Book. { public int BookId { get; set; }

What is one to many relationship in Entity Framework?

In this article, we will cover one-to-many relationships between entities. A one-to-many relationship happens when the primary key of one table becomes foreign keys in another table and also this primary key should participate in the primary key of the second table.

How do you create a relationship between two tables in Entity Framework?

You can create such a relationship by defining a third table, called a junction table, whose primary key consists of the foreign keys from both table A and table B.

Which are the correct Fluent API methods for describing relationships?

When configuring a relationship with the fluent API, you start with the EntityTypeConfiguration instance and then use the HasRequired, HasOptional, or HasMany method to specify the type of relationship this entity participates in.


1 Answers

You basically answered your own question, as the two things you describe are separate:

  1. Unlinking the object
  2. Deleting the object

There may be a clever way for EF to do this, but others have asked the same question and been presented with the answer you alluded to:

e.g. EF 4.1: Removing child object from collection does not delete it - why?

like image 96
Matthew Avatar answered Nov 15 '22 00:11

Matthew