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()
?
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; }
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.
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.
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.
You basically answered your own question, as the two things you describe are separate:
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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With