How to Clear() all elements from Entity Framework ICollection? : <p>I have problems removing all elements from a collection in entity framework using Clear()</p>

<p>Consider the often used example with Blogs and Posts.</p>

<pre><code>public class Blog
{
    public int Id {get; set;}
    public string Name {get; set;}
    public virtual ICollection&lt;Post&gt; Posts { get; set; }
}

public class Post
{
    public int Id { get; set; }

    // foreign key to Blog:
    public int BlogId { get; set; } 
    public virtual Blog Blog { get; set; }

    public string Title { get; set; }
    public string Text { get; set; }
}

public class BlogContext : DbContext
{
    public DbSet&lt;Blog&gt; Blogs {get; set;}
    public DbSet&lt;Post&gt; Posts {get; set;}
}
</code></pre>

<p>A Blog has many Posts. A Blog has an ICollection of Posts. There is a straightforward one-to-many relation between Blogs and Posts.</p>

<p>Suppose I want to remove all Posts from a Blog</p>

<p>Of course I could do the following:</p>

<pre><code>Blog myBlog = ...
var postsToRemove = dbContext.Posts.Where(post =&gt; post.BlogId == myBlog.Id);
dbContext.RemoveRange(postsToRemove);
dbContext.SaveChanges();
</code></pre>

<p>However, the following seems easier:</p>

<pre><code>Blog myBlog = ...
myBlog.Posts.Clear();
dbContext.SaveChanges();
</code></pre>

<p>However this leads to an InvalidOperationException:</p>

<p><em>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.</em></p>

<p>What is the proper way to clear the collection? Is there a fluent API statement for this?</p>
