title: GUID or int entity key with SQL Compact/EF4?
body: <p>This is a follow-up to an <a href="https://stackoverflow.com/questions/2480084/generating-entity-keys">earlier question</a> I posted on EF4 entity keys with SQL Compact. SQL Compact doesn't allow server-generated identity keys, so I am left with creating my own keys as objects are added to the <code>ObjectContext</code>. My first choice would be an integer key, and the previous answer linked to a <a href="http://sibagy.spaces.live.com/blog/cns!D96C7B6CE19A2F61!1152.entry" rel="nofollow noreferrer">blog post</a> that shows an extension method that uses the <code>Max</code> operator with a selector expression to find the next available key:</p>
  
  <pre><code>public static TResult NextId&lt;TSource, TResult&gt;(this ObjectSet&lt;TSource&gt; table,  Expression&lt;Func&lt;TSource, TResult&gt;&gt; selector) 
      where TSource : class
  {
      TResult lastId = table.Any() ? table.Max(selector) : default(TResult);
  
      if (lastId is int)
      {
          lastId = (TResult)(object)(((int)(object)lastId) + 1);
      }
  
      return lastId;
  }
  </code></pre>
  
  <p>Here's my take on the extension method: It will work fine if the <code>ObjectContext</code> that I am working with has an unfiltered entity set. In that case, the <code>ObjectContext</code> will contain all rows from the data table, and I will get an accurate result. But if the entity set is the result of a query filter, the method will return the last entity key in the filtered entity set, which will not necessarily be the last key in the data table. So I think the extension method won't really work.</p>
  
  <p>At this point, the obvious solution seems to be to simply use a GUID as the entity key. That way, I only need to call <code>Guid.NewGuid()</code> method to set the ID property before I add a new entity to my <code>ObjectContext</code>. </p>
  
  <p>Here is my question: Is there a simple way of getting the last primary key in the data store from EF4 (without having to create a second <code>ObjectContext</code> for that purpose)? Any other reason not to take the easy way out and simply use a GUID? Thanks for your help.</p>