title: Entity Framework Relation with null or 0 Key
body: <p>I am trying to work with an existing database and my ability to make changes are difficult. I am hoping to do some transitional work and being an ORM in however, i have hit an issue.</p>
  
  <p>I am using EF Fluent API (closer to the NHibernate way of doing things) and we have a nullable column <code>ParentId</code> in the database. I have created a <code>HasOptional</code> relationship for this and it works:</p>
  
  <pre><code>HasOptional(x =&gt; x.Parent).WithMany().Map(m =&gt; m.MapKey("ParentId"));
  </code></pre>
  
  <p>This particular column seems to have a lot of 0's in this column (they don't use foreign keys) and I may not be able to add a FK constraint as that my break their other applications (as I would need to go though and alter / delete everything that doesn't have a FK match). EF does handle this well enough and for these records that don't have a matching parent for id 0, EF gets null. This however falls over if I try to use a Linq query like this:</p>
  
  <pre><code>myitems.Where(i =&gt; Parent != null)
  </code></pre>
  
  <p>to select everything where <code>Parent != null</code>. This translates this type of SQL query</p>
  
  <pre><code>WHERE ParentId = null
  </code></pre>
  
  <p>This of course does not get the desired results as it returns the records that have a <code>ParentId</code> of <code>0</code>. When I inspect the object, as expected based on this SQL query, I get results that both have parent correctly and many that have parent as null. </p>
  
  <p>Is there a way to get EF to translate this column in its queries to something like <code>NULLIF(0)</code>? If not, I need some ideas on how I can work around this so I can use EF without having to cause breaking changes in the database.</p>
  
  <p>I have already considered a computed column, but that would only help me on the querying. It will fall over if I ever try to persist the entity.</p>