سؤال

    protected Server getServerByName(string name)
    {
        var servers = from qServer in db.Servers
                      where qServer.Name == name
                      select qServer;

        if (servers.Count() > 0)
        {
            return servers.First(); // The error occurs on this line
        }

        return null;
    }

This code has been working as expected up until now, however today it suddenly started giving this error:

An exception of type 'System.Data.Entity.Core.EntityCommandExecutionException' occurred in mscorlib.dll but was not handled in user code Additional information: An error occurred while executing the command definition. See the inner exception for details.

I can't understand the error, even less than I can understand how this can happen. Does anyone have any idea why this is happening?

هل كانت مفيدة؟

المحلول 3

After checking the InnerException, I found that I hadn't migrated the last model change to the database (EF CodeFirst). This exposed that I had added a column to the model without doing so to the database, and as a result it wouldn't obtain the object.

Fixed by migrating, although I'd like to thank martin_costello and Ehsan Sajjad for the FirstOrDefault tip, which makes my code look a lot nicer.

نصائح أخرى

Whilst this doesn't answer your question directly, your code is inefficient as you're performing two SQL queries. You should use FirstOrDefault() instead, which will return null if there are no servers found.

protected Server getServerByName(string name)
{
    var servers = from qServer in db.Servers
                  where qServer.Name == name
                  select qServer;

    return servers.FirstOrDefault();
}

Try this simplification and see if the original problem goes away.

Use FirstOrDefault() it will not throw exception if no record available.

return servers.FirstOrDefault();

It will simply return null if no item available.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top