I’ve built an F# app and now I’m using EF4.1 (code first) as a data store. I’ve stumbled upon a really quirky issue around typing.
Take the following snippet:
let result = context
.SearchResults
.Where((fun (r:SearchResult) ->
r.Program = request.Program))
.OrderByDescending((fun r -> r.AcquisitionDate))
.FirstOrDefault()
match result with
| price ->
cacheProvider.Set(result)
Some(price)
| _ ->
ignore(context.SearchRequests.Add(request))
ignore(context.SaveChanges())
None
when the search result does not exist, the .FirstOrDefault() call returns null. So result is bound to null during runtime. But at compile time the F# compiler expects that result will never be null so I can’t do pattern checking around null (price when price <> null).
What am I missing here? Is there a proper way to do this?
You can test for equality against
Unchecked.defaultof<_>instead of null.