Entity Framework Performance Tip: Disable Automatic Change Detection for Bulk Operations

A dev on the EF team says some stuff here about Entity Framework’s automatic change detection that I think we might find valuable:

When you need to manipulate many entities … the advice is to switch off AutoDetectChanges while you, for example, do all your Adds, and then switch it back on again afterwards.

You can turn off automatic change detection at the context level like this:

myContext.Configuration.AutoDetectChangesEnabled = false;

I haven’t looked at the performance improvements you get from this, but this post makes me think the performance would go from quadratic to linear. That’s a big boost.

(Here’s another well written post on the matter.)

Precision in Communication

A great developer would be good at two very different kinds of communication: communication with the compiler/interpreter and communication with other humans. Skills or techniques that benefit one of these modes of communication are often at odds with those that would benefit the other. E.g.: precision.

If I’m communicating with a compiler, the ability to be precise is valuable. At a very basic level, I have to be precise with my variable names. If I declare a variable “foo”, I can’t spell it “phoo” elsewhere and expect the compiler to know what I mean. (Sure, in some languages I could change casing and it might work. That’s slightly less precise, but still a degree of precision.)

On the other hand, when you’re trying to communicate with people, precision is often the opposite of what you want. If I needed to explain the first fundamental theorem of calculus to you, I could do it like this:

first-fundamental-theorem

That would be precise. Do you think that’s the best way of communicating the information? To someone who doesn’t know it? No, of course not. In a calculus class, you build to it with proofs and cement it with examples. That’s redundancy, which programmers are generally taught to despise, but in this context it’s valuable.

Communicating with businesspeople, whether for requirement gathering or support or what-have-you, is like that. You’ll often benefit from repeating yourself, especially if you frame information differently to help the other party understand what you’re trying to get across. Use examples. Ask obvious questions or state the obvious. Make the other person repeat what you just said back to you, or repeat it back to them. It feels uncomfortable, but it helps.

(Other developers can be a whole other story with respect to this. Some of us prefer precise communication, some of us don’t. I’d actually go so far as to say being a great developer would require being good at three very different modes of communication: with the compiler, with the businesspeople, and with other developers. Perhaps I’ll write about that some time.)

Javascript objects are kinda like hash tables

If I make an object like this:

var myObj = {
   key1: "foo",
   key2: "bar",
   key3: function() { return "Hi."; }
};

I can access those properties like this:

var myKey = myObj.key1; // assigns myKey the value "foo"
var myFunction = myObj.key3 // assigns myFunction the function function() { return "Hi."; }

Or like this:

var myKey = myObj["key1"]; // assigns myKey the value "foo"
var myFunction = myObj["key3"] // assigns myFunction the function function() { return "Hi."; }

These two styles are logically equivalent. However, the dot notation is preferred according to most JS nerds.

I think the second style can, in some situations, be more convenient or clearer about what the code is doing. But your mileage may vary.

Simple jQuery.extend() Example

jQuery’s extend method does a memberwise copy of one or more objects onto a target object and returns the altered target object.

For example, say I have an object that represents some default options, like this:

var defaultOptions = {
   foo: "foo",
   bar: "bar"
};

var options = {
   foo: "hmm",
   derp: "derp"
};

If I call $.extend({}, defaultOptions, options), I’ll get back this result:

{
   foo: "hmm",
   bar: "bar",
   derp: "derp"
}

This is handy when you want to have default options in a private member, then pass in an options object that only overrides what you configure and leaves the rest of the defaults alone.

Getting Entity Framework’s ExecuteStoreQuery Method to Return Attached Objects

When you call myObjectContext.ExecuteStoreQuery<TEntity>(string commandText, param object[] parameters), the objects returned are detached from the object context. You might have to jump through some hoops to get them attached to your context. (It wants to treat them as new instances, and you’re like WTF.)

If you want the returned entities to be added to your context, there’s an overload to ExecuteStoreQuery that lets you specify an entitySetName parameter and a mergeOption parameter. The entitySetName parameter is the name of the entity set in the object context you want your objects to go into, and the mergeOption specifies options about whether the results returned should overwrite stuff that might already be in your object context.

Compile Views in an ASP.NET MVC Project

By default, an ASP.NET MVC project doesn’t compile Razor view code when you build it. Hence, errors in the views don’t get caught at compile time.

Sometimes, if I quickly want to see if a change has caused any compilation errors in my views, I’ll open my project file in a text editor and edit this element:

<MvcBuildViews>false</MvcBuildViews>

Set the value to true and you can see if your views compile. I’ll usually set it back to false when I’m done, though you certainly don’t have to.

JS Convention for Null/Empty Checks

This:

if (value) {
}

will evaluate to false if value is null, undefined, NaN, an empty string, 0, or false.

So you should never need to do any of the following:

if (value == null) {
}
if (value == undefined) {
}
if (value == "") {
}
if (someString.length == 0) {
}

The common JS version of all these is simply

if (value) {
}

It makes for cleaner code and smaller files, too.

Notes on jQuery’s data() and attr() functions

If I have a DOM element

<div id="myDiv"></div>

and I call

$("#myDiv").data("id", 1)

I might expect it to be updated like so:

<div id="myDiv" data-id="1"></div>

But that’s not how jQuery’s .data() method works. It attaches the data to the element in its internal data store, but it doesn’t update the DOM element itself.

If I want to set the actual attribute in the HTML, I have to call

$("#myDiv").attr("data-id", 1);

In either case, though, jQuery’s .data() method can read the value like this:

var value = $("#myDiv").data("id")

It gives precedence to its internal data store, but will fall back to a data-whatever property on the DOM node, if it’s there.

Web API Namespaces vs MVC Namespaces

tl;dr: You should never have references to System.Web.Mvc.* in an ApiController.

One thing that took me longer than I’d care to admit to realize when working with Web API and ApiController is that Web API has its own namespace to do a lot of the stuff I was used to System.Web.Mvc doing.

So, for example, there’s a System.Web.Mvc.HttpPostAttribute class that you’d use to decorate a controller action to tell it to accept HTTP POST requests.

If you’re trying to do that on an ApiController action, you’ll want to use System.Web.Http.HttpPostAttribute.

The code ends up looking the same, mostly, though, because instead of including using System.Web.Mvc; at the top, you’ll have using System.Web.Http, and you’ll end up writing the attribute as just [HttpPost].

This doesn’t just apply to those attributes, either. Web API uses that System.Web.Http stuff for action filters, configuration, and plenty of other stuff. You should never need to include System.Web.Mvc.* for anything in an API controller.

Simple JS Prototype Example

This is some boilerplate code I sent out recently to describe the JS prototype code I’d been writing:

// create a global MyClass object, intialized to the result of this anonymous, self-executing function
var MyClass = (function() { 

   // constructor function, intializes stuff
   function MyClass($el, options) {
      var self = this;
      self.options = options;
      self.$el = $el;
   } 

   // put functions on the prototype for the constructor function
   MyClass.prototype = {
      myPublicFunction: function() {
         this.$el.doSomething();
      }
   } 

   // return the constructor function, so the MyClass outside of this closure becomes a function
   return MyClass;
});

You can then create an instance of MyClass like this:

var myClass = new MyClass($("#element"), myOptions);

With this pattern, not only can you create multiple instances of the class, but they’ll inherit the same prototype, which means all those prototype functions only get created once, not once for each object you create.

It’s also worth pointing out that it’s a JS convention to only capitalize function names when they’re meant to be used with the “new” keyword, to be treated as objects.

Fun times.