0

I had a test case that looks like this:

[TestMethod]
public void Things_can_be_saved()
{
  var ts = DateTime.Now;
  var thing = new Thing()
  {
      Name = "Some name",
      TimeStamp = ts
  };

  // save it
  var context = new MyDataContext(testDb);
  context.Things.Add(thing);
  context.SaveChanges();

  // pull from a fresh context so we know it's a db pull not cached
  var context2 = new MyDataContext(testDb);
  var fetched = context2.Things.FirstOrDefault(t => t.TimeStamp == ts);

  Assert.AreEqual(thing.Name, fetched.Name); 
}

So, when I run this, I can look in the DB and see 'thing' present in the db. I can see that the stored Timestamp column for it is equal to the value in the ts variable at runtime. But 'fetched' is null, indicating that EF can't find it in the FirstOrDefault query. Is there something I'm missing about DateTime equality?

Paul
  • 35,689
  • 11
  • 93
  • 122
  • What's the column type on the database? Also, if you're using the EDMX designer, can you check what's the *StoreGenerationPattern* setting for property `TimeStamp`??? – Fernando Espinosa Nov 07 '12 at 21:56
  • You probably need to change your column in the database to be datetime2 instead of datetime – Pawel Nov 08 '12 at 04:09
  • This is all codefirst, sorry if that wasn't clear when I asked the question. – Paul Nov 08 '12 at 05:43
  • @Pawel, that was exactly the problem. If you turn your comment into an Answer I'll accept it. – Paul Dec 03 '12 at 02:49

1 Answers1

2

You probably need to change your column in the database to be datetime2 instead of datetime

Also see this thread: DateTime2 vs DateTime in SQL Server

Community
  • 1
  • 1
Pawel
  • 31,342
  • 4
  • 73
  • 104
  • +1 but wouldn't it be a better answer if it linked to http://stackoverflow.com/questions/1334143/sql-server-datetime2-vs-datetime? – Mathieu Guindon Mar 06 '13 at 05:30
  • Feel free to edit it - stackoverflow is about having good answer so if you can improve - go for it. I just was not aware about the other thread. – Pawel Mar 06 '13 at 06:16
  • @retailcoder for some reason I was not able to approve your edit. Edited the answer and added the link you provided. – Pawel Mar 06 '13 at 07:18