A WTF moment with Entity Framework 4.0

Table Design in SQL Express 2008 R2

Figure 1: Business Table design. You will notice that the letter row is marked as a 1 charcter "char" type.

I’m currently working a new website that uses Entity Framework 4.0 as it’s data access layer. I’m still learning the ropes as it’s the first time I’ve used Entity Framework in a project, but the way Entity Framework handles T-SQL char data types struck me as being quite odd. Specifically the fact that Entity Framework maps char to String.

Figure 2: Mapping Details in EF 4: Notice that the letter row is now mapped as a String data type?

I would have thought that a T-SQL char data type would be mapped to the equivalent .Net char data type.

It’s my understanding that the String data type is a Class instead of being an value type or structure, and that its essentially an array or sequence of System.Char unicode characters. Not to mention Strings are immutable, so WHY map a Char to String?

It’s actually caused me a good 15 minutes of pain, simply because I didn’t bother to look at the mappings. Essentially what I was trying to do was return a IQueryable of my Business entities based on this particular character field. Guess what, passing a char when .Net expects a String doesn’t work.

public IQueryable<Business> getBusinessesByChar(char charAlpha) {
 return db.Businesses.Where(b => b.letter.Equals(charAlpha));
 }

Doesn’t Work..
“Unable to create a constant value of type ‘System.Object’. Only primitive types (‘such as Int32, String, and Guid’) are supported in this context.”
Que?

public IQueryable<Business> getBusinessesByChar(char charAlpha) {
 return db.Businesses.Where(b => b.letter.Equals(alpha.toString()));
 }

Doesn’t Work..
“LINQ to Entities does not recognize the method ‘System.String ToString()’ method, and this method cannot be translated into a store expression.”
Great..

public IQueryable<Business> getBusinessesByChar(char charAlpha) {
 //SCREW YOU EF!!
 String alpha = charAlpha.ToString();
 return db.Businesses.Where(b => b.letter.Equals(alpha));
 }

That works.. Seriously.. How is creating a new String object and passing it to LINQ any different from using the char.ToString() method?

If anyone out that feels like cluing me in, then by all means, I gave up trying to work it out after 15 mins.

This entry was posted in Entity Framework and tagged , , . Bookmark the permalink.

One Response to "A WTF moment with Entity Framework 4.0"

Leave a reply