title: Is it possible to remove child from collection and resolve issues on SaveChanges?
body: <p>We are using Entity Framework Code First with Foreign Key relationships. We investigating on ways on handling removing objects from an entities ICollection in our application. </p>
  
  <p>When we have an entity with child relationships we can add objects directly to their ICollection using Add method. Now when you use remove you get the error</p>
  
  <blockquote>
    <p>System.InvalidOperationException occurred Message=The operation
    failed: The relationship could not be changed because one or more of
    the foreign-key properties is non-nullable. When a change is made to a
    relationship, the related foreign-key property is set to a null value.
    If the foreign-key does not support null values, a new relationship
    must be defined, the foreign-key property must be assigned another
    non-null value, or the unrelated object must be deleted.</p>
  </blockquote>
  
  <p>I understand this is because Remove on the collection only deletes the relationship by nulling the foreign key. We wanted to write our business logic in our entity and allow removal. </p>
  
  <p>So get root entity out out of  it's Repostiory e.g Order from OrderRepository then call some specific method of the entity e.g. <code>Order.AddOrderline(Orderline orderline)</code> This adds an OrderLine to the Orders <code>virtual ICollection&lt;OrderLine&gt; OrderLines</code></p>
  
  <p>However we can't write code like <code>Order.CancelOrderline(int orderLineId)</code> because simply removing from the ICollection causes an error on savings changes.</p>
  
  <p>There doesn't seem to be anyway to achieve this by just manipulating the object collections. Obviously we can remove directly from Context. However I'd like to make it part of the entity. Can we clean up certain entities with no foreign key on SaveChanges event of Entity Framework? Obviously need to tell EF what entities can be removed if they have null foreign key.</p>
  
  <p>We presently are using a repository pattern so the controller doesn't have access to the context. I could obviously use an OrderLine repository or a remove OrderLine method on the Order repository. However just wondering if it was possible to write the code on the entity without references to the persistence mechanism.</p>
  
  <p>Thoughts? Are we going about this all wrong? Do other ORMs allow you to just remove from Child Collections? </p>