title: Creating entity with DateTime in primary key
body: <p>Suppose we have "EfTest" database with the following table in SQL server:</p>
  
  <pre><code>create table Test
  (
      Id INT NOT NULL IDENTITY(1,1),
      TS DATETIME NOT NULL
      PRIMARY KEY (TS, Id)
  )
  </code></pre>
  
  <p>And we want to add stuff there with EF (EF 5 in my case). We create edmx file from database in our sample project and write following code:</p>
  
  <pre><code>    static void Main(string[] args)
      {
          var ctx = new EFTestEntities();
  
          var t = new Test();
          t.TS = DateTime.Now;
  
          ctx.Tests.Add(t);
  
          ctx.SaveChanges();
      }
  </code></pre>
  
  <p>We run it and it fails with <code>DbUpdateConcurrencyException</code> on <code>ctx.SaveChanges()</code> line, saying: </p>
  
  <blockquote>
    <p>Store update, insert, or delete statement affected an unexpected
    number of rows (0). Entities may have been modified or deleted since
    entities were loaded. Refresh ObjectStateManager entries.</p>
  </blockquote>
  
  <p>Obviously, no concurrency happening there. SQL Server profiler reports that following query is run by EF:</p>
  
  <pre><code>exec sp_executesql N'insert [dbo].[Test]([TS])
  values (@0)
  select [Id]
  from [dbo].[Test]
  where @@ROWCOUNT &gt; 0 and [Id] = scope_identity() and [TS] = @0',N'@0 datetime2(7)',@0='2015-08-27 18:29:45.1025442'
  </code></pre>
  
  <p>Problem lies here: <code>@0 datetime2(7),@0='2015-08-27 18:29:45.1025442'</code>. <code>DATETIME2</code> is higher precision than <code>DATETIME</code> and <code>TS</code> check in the <code>WHERE</code> clause prevents it from finding the row it just inserted.</p>
  
  <p>Question: putting aside the reason why I have <code>DATETIME</code> column as part of PK, how do I make EF to insert rows without throwing exceptions?</p>
  
  <p><del>I could make <code>TS</code> column to be of <code>DATETIME2</code> type, which would resolve the issue, but I don't want to waste DB space just because of some EF issue.</del> I double checked and it seems both <a href="https://msdn.microsoft.com/en-us/library/ms187819.aspx" rel="nofollow"><code>DATETIME</code></a> and <a href="https://msdn.microsoft.com/en-us/library/bb677335.aspx" rel="nofollow"><code>DATETIME2</code></a> occupy 8 bytes, so I guess I go that way.</p>
  
  <p>I could edit <code>.edmx</code> file in text editor and make it think that primary key is <code>Id</code> column only (so EF wouldn't use <code>TS</code> to lookup <code>Id</code> after insert), but VS will overwrite my edits next time I update entities from DB.</p>
  
  <p>Any other options?</p>