2

Resolved

EntityFramework CRUD scaffolding template incorrectly uses Single()

description

The templated Delete action for an "API controller with read/write actions, using Entity Framework" produces the following code:
        Platform platform = db.Platforms.Single(p => p.Id == id);
        if (platform == null)
        {
            return Request.CreateResponse(HttpStatusCode.NotFound);
        }
If I'm not mistaken, Single will throw on a null/no elements in sequence, and so the null check in the 2nd line will never run and the 404 will not be returned.

The template needs to be updated to use SingleOrDefault.

Thanks!

comments

lukepuplett wrote Jun 19, 2012 at 6:24 PM

Actually, GetXxx uses the same pattern which makes me wonder if this has already been reported, or even if I'm wrong!?

lukepuplett wrote Jun 19, 2012 at 6:27 PM

Okay, technically speaking the provider can return null, which I assume EF does, so maybe this is more about expected semantics and EF than it is about the scaffolding template.

HongmeiG wrote Aug 13, 2012 at 5:30 PM

We should use Db.Platforms.Get instead of Single.

HongmeiG wrote Mar 12 at 9:54 PM

Maybe we can just use .Find(Id) instead.

HongmeiG wrote Mar 12 at 10:44 PM

I just tried the latest VS2012.2 bits, and it no longer repros.