title: Entity Framework: how to delete related entity upon update or delete of 'generic' parent
body: <p>I have a <code>Product</code> class, which contains a <code>Picture</code> property. Other classes may also have a picture, e.g. a <code>Customer</code> can have a <code>Picture</code>.</p>
  
  <p>Product.cs:</p>
  
  <pre><code>public class Product
  {
      public Picture Picture { get; set; }
  } 
  </code></pre>
  
  <p>Customer.cs:</p>
  
  <pre><code>public class Customer
  {
      public Picture Picture { get; set; }
  } 
  </code></pre>
  
  <p>Picture.cs:</p>
  
  <pre><code>public class Picture
  {
      public string Type { get; set; }
  
      public byte[] Content { get; et; }
  }
  </code></pre>
  
  <p>The <strong>picture is always optional</strong>, i.e. Products and Customers may or may not have a picture. However, a picture is uniquely linked to exactly one 'parent' entity (either a Product or a Customer). Without the parent, there's no use for the Picture to exist. Note that there's no link from Picture to the parent class, because this parent can be of multiple types (Product or Customer).</p>
  
  <p>Another requirement is that I want to have full control over whether the picture is loaded or not, through <strong>eager or lazy loading</strong>. E.g. when retrieving a list of products, I don't want the picture to be fetched, but if a single product is requested, the picture should be included.</p>
  
  <p><strong>My question</strong>: how can I configure Entity Framework so that:</p>
  
  <ul>
  <li>The Picture record is deleted when the parent (product or customer) record is deleted</li>
  <li>The Picture record is deleted whenever the parent record is updated and the new version does not contain a picture</li>
  <li>The Picture record is replaced (delete + create of a record) whenever the parent is updated with a new picture</li>
  <li>The picture is optional</li>
  <li>Always keep control over whether the picture is loaded or not</li>
  </ul>
  
  <p>I'm using <strong>fluent API</strong> to define the relationship. Currently, there's no cascading delete whatsoever.</p>
  
  <pre><code>public class ProductMap : EntityTypeConfiguration&lt;Product&gt;
  {
      public ProductMap()
      {
          ToTable("PRODUCTS");
  
          HasKey(x =&gt; x.Id);
  
          HasOptional(x =&gt; x.Picture).WithOptionalDependent().Map(m =&gt; m.MapKey("PICTUREID"));
      }
  }
  </code></pre>
  
  <p>I tried using WithRequired but this generates errors because there's no link or foreign key from <code>Picture</code> to <code>Product/Customer</code>.</p>