Search

Based on comments that an angry mob of EF users left, I decided that I needed to take another look at EF4.

First off: you can use POCOs in EF4 without the CTP. It can be done. Now please stop throwing bricks through my windows!

I did another spike branch using the above linked tutorial. Compared to the CTP code-first approach, it’s a tiny bit clunky, but compared to the standard inherit-from-EntityObject approach, it’s much much better. I think that you can use T4 to generate your POCOs from the class designer even, so that’s an option too.

Some other notes:

The repository implementation was exactly the same as before. Craig Stuntz, who has been extremely and selflessly helpful has suggested that I modify the repository slightly to use GetObjectStateEntry instead of checking if the id is 0. That is an idea that makes sense, but I just haven’t done it yet, as I still need to figure out the whole attached/detached thing and other implementation details of EF. But if I were you, I’d take his advice.

Let me withdraw my blanket “F” grade of EF. There are a lot of facets to EF, some of them get an “A” (code-first POCO) and some of them still get an “F” (EntityObject). Overall, EF4 gets a “passing” grade (hows that for diplomatic?).

Coming into these comparisons, NHibernate is the OR/M I’ve used the most, and the one I’m biased towards (although code-first POCOs in EF have really impressed me).

A brief overview of NHibernate if you’ve not used it before: It’s an OR/M just like EF, based on the Hibernate library from Java. Each class maps to a database object via an XML configuration file. An NHibernate “session” is opened to interact with the database (similar to an EF “context”). The biggest complaint about NHibernate is usually the messy XML files that needed to be created. Fluent NHibernate aims to solve that by moving these XML mapping files into C# mapping classes, so you get intellisense, compile time checking, etc, and as a bonus you get a fluent configuration API too. Another complaint about NH, is that for querying, NHibernate uses HQL, the Hibernate Query Language, and not Linq. I don’t really like the HQL API, so that’s why I like to use the NHiberate.Linq library as much as possible, which brings native Linq support to NHibernate. (If all these extra libraries seem intimidating, well, that’s what NuGet is for :)

Some more notes about Fluent NH:

While NHibernate allows us to use POCOs for our entity objects, one annoying thing is that the entity properties have to be marked as virtual. Other than that, they stay the same. While the ‘virtual’ thing isn’t a big deal, I think EF POCOs get the leg up here, as they require zero change to the actual entities.

I wrote a ProductMap class to do the object-relational mapping. However, there is also a convention-based approach that doesn’t require using explicit mapping classes. However, I’ve found that this can be more trouble than it’s worth for all but the very simplest domains.

There was some weirdness with NHibernate.Linq when I tried to select and order all distinct categories (see NavController here). The NHibernate.Linq library 1.0 release was late last year, and I think there is more work needed on it to get the Linq support up to snuff, but I think it’s 90% of the way there.

I used a session-per-request pattern via StructureMap and the EndRequest event in Global.asax.cs. This means that the repository doesn’t have to worry about opening/closing/disposing the NH session, and gives a basic unit-of-work pattern to each web server request. This can be implemented in other ways (HttpModule, for instance). I didn’t do this yet with EF, because doing it with NH has become a part of my normal NH ritual, I guess. I’ll definitely talk about this pattern in a separate post.

I had some trouble with the Image upload, and it’s because Fluent-NH doesn’t really know how to handle varbinary(max) by default (though regular NH appears to handle it fine). See this commit on Github to see how I got it to work. The image-stored-in-the-database thing has been a sticking point for both EF and NH, just in different ways. I usually prefer to store images in the file system, and if you do too, then this is pretty much a non-issue.

I’ve been throwing around this term: POCO this and POCO that. POCO stands for “Plain Old CLR Object”, and it just means that you can use a class with an OR/M without that class inheriting from some base class that the OR/M provides. Many OR/M users (including myself) prefer OR/Ms that support POCOs because it means that the OR/M technology can be confined to hide behind an interface, and the rest of the application doesn’t care which OR/M is being used.

As I showed in the last post, standard EF does not use POCOs and thus its tendrils snake throughout your application (though apparently there is a way to accomplish this without the CTP, I just haven’t figured it out yet). But never fear lovers of closed-sourced Microsoft sanctioned tools: EF will soon allow the use of POCOs. This “code first” method is the most appealing to me, because it reminds me the most of Fluent-NH (let me disclose that bias so you know where I’m coming from). Write a bunch of entity classes, then write a subclass of DbContext which contains DbSets of those classes. Use this DbContext subclass to interact with the database (the same API as the above two methods). Specify a standard SQL connection string (there’s a convention in place so that’s optional), and when the application first fires up that DbContext object, the SQL database/object will all be generated out on the db server. Nice.

Some more notes on code-first EF4:

This was a much, much easier implementation, obviously, since I could use my existing entities, no problem. I updated my StructureMap config to use the new implementation, and that was it. Again, I did not do a unit-of-work implementation yet for EF, so I still have to go back and do that.

A standard SQL connection string works fine.

While I found this implementation very easy, there are a lot of factors to consider when the tables are generated, hosed, and regenerated during development. If your testing involves some sort of data baseline, then it would be a good idea to run that baseline whenever the model changes during development (the generation/hosing/regeneration can be configured in the Application_Start event in the Global.asax.cs). If you are using a shared database, you should also be mindful when regenerating (or checking in changes that will cause regenerating), as this will hose all the data.

The code-first EF4 stuff is not part of the current EF4 release. It is CTP (community tech preview) 4, and thus the features & API are not set in stone. Check out ScottGu’s blog post for details and a download link.

I’ve never used EF before, and to be honest, I have pretty strong biases against it for a number of reasons. However, it deserves a fair shake, so here goes.

ef.jpg

The standard EF approach is similar to Linq-to-SQL. You first create database objects (tables, views, SPs). Then you add a new “Entity Data Model” to the project, select the DB objects you want to model via a wizard, and EF will generate all the objects/SQL/etc that you need to interact with the database. (There is a “model first” approach where you define classes first and the SQL objects/scripts get generated. It’s essentially the same approach in reverse).

With standard EF4, POCOs can’t be used, so I basically had to rip out all references to my existing entities and replace them with EF4′s entities. This was painful just for this tiny app with one entity. Going back the other way would be equally painful. If I built the app to use EF objects in the first place, this part wouldn’t have been painful. However, as one of my goals is to keep the implementation behind an interface, using EF in the standard way simply doesn’t work.

Some more notes:

EF4 generates a wacky SQL connection string when creating the Data Model. Compared to the above offense of not using POCOs, this ranks pretty low as a problem.

Other than gutting my existing entities, implementing the repository interface was easy enough, but it took me a couple of commits to get it right, since I’ve never used EF4 before (have I mentioned?) I didn’t put a unit-of-work pattern into place, so I might still need to do that (and as I write this, that comment was just made to the previous blog post :) .

One wacky thing to mention is the code to read an uploaded image via an input stream: it didn’t work if I used the entity’s property as a buffer directly, I had to switch to an intermediate buffer byte array.

Since the entity classes are generated, I had to put all the DataAnnotations metadata into their own “buddy” classes (see this commit). Opinions on buddy classes can vary widely. I’m not a big fan of the repeated bits of code, but I don’t think it’s necessarily a total dealbreaker.

My grade for standard EF is pretty much an “F”. Since POCOs aren’t used, EF gets its hooks in a large part of your code. This is the EF that I heard so many complaints and formed my biases about, and I now I can safely say it’s deserving. It might be a good solution for small, simple apps, and it makes a good demo, but that’s about all I can say positive about it.

HOWEVER, there is an EF4 POCO solution, and while it’s only a CTP right now, it’s very encouraging, and very interesting, and I’ll cover it in the next post.

I have recently been looking at OR/M solutions, most notably EF4 and NHibernate for a couple of reasons:

  • To familiarize myself with EF (I’ve never used it before)
  • To find the pros/cons to ultimately help decision makers to decide which is more suitable

As of now, I’ve only looked at EF4 (both standard and “code first” versions), and (Fluent) NHibernate. There are certainly other fine OR/Ms (LightSpeed, SubSonic, Castle ActiveRecord) that I may spike out in the future, but as for now I’m only working with the two heavyweights. I also did a Linq-to-SQL spike, but I probably won’t be blogging much about it.

I have been working on a sample MVC3 app called “SportsStore”, which is based on the SportsStore in Steven Sanderson’s book on MVC2. This app uses a Repository pattern for the data access layer, and has a Linq-to-SQL implementation as a sort of “default”. You can find this example app in my SportsStore project on GitHub in the master and/or develop branches. I’m also using StructureMap as an IoC container.

My idea was to implement the same repository interface (IProductsRepository) using each of the OR/M tools, with a branch for each, and use that as a basis for comparison. One of my goals was to keep the implementation details hidden as much as possible behind that IProductsRepository interface. If you want to skip ahead, you’ll see that there are three branches: ef4_spike, ef4_code_first, and fluent_nh.

A central goal of these posts is to solicit feedback. What am I doing wrong, what am I doing right, what could I be doing better? So please, be brutal, be honest, and be vocal.

I’ve been working with Razor some recently, and here are a couple of surprises that bit me.

razorwire.jpg

First, I had a block of JavaScript in a view, and I was getting a parsing error on the “less than” sign in a JavaScript “if” statement. The problem was that my JavaScript block was, itself, inside of a Razor block (a ‘using’ block actually), so Razor was having trouble parsing it. I just moved the JavaScript out of the block and Razor handled it fine. See: “Tag is missing a name” with Razor on Stack Overflow for more details.

Secondly, I was writing an HtmlHelper extension method. I put the namespace in the pages/namespaces Web.config block, but my Razor view didn’t seem to be able to find it. Apparently, Razor uses a different configuration block for this, which is kinda annoying. For details, check out Razor (MVC 3 RC) HtmlHelper Extensions Not Found on Stack Overflow. According to Marcin Dobosz (who left a comment on that SO page), this is not something they are going to fix/change. However, if you are using Razor, it looks like you can remove the standard pages/namespaces block from the Web.config.

On my Monodroid app, I have a list of portfolios. When a user clicks on that portfolio, they should be sent to a child activity to see information about the portfolio they clicked on. I already blogged about how to open a new activity, so now I’m going to blog about how I pass information to that activity (for instance, the name of the portfolio). Android calls this information “extras”.

I have a ListView with an ItemClick event already wired up. Here is the ItemClick event:

Again, the ClassName property is just something I cooked up to hold a string value (see above linked blog post). Notice the main difference is that I’m calling the “PutExtra” property on the intent. This is pretty much just a way to box information up and send it to the next activity. The “Extra_PortfolioID” property is, again, just a string, and an arbitrary string at that which acts as a “key”. I’m passing an ID (a long in this case) to the next activity as the “value”. (The coalesce operator is because my entity has nullable ints, but the -1 will never be used in this case).

Over in the PortfolioActivity, I simply use Intent.GetLongExtra(Extra_PortfolioID, -1); to get the ID number out back out of the intent object. I’m again using that arbitrary Extra_PortfolioID string as the key. The “-1″ is the default value, since technically the data is being serialized, but because of the way I’ve written the app, that value won’t ever be used. Then I can query my database with that ID or do whatever I need to do.

Here are the slides/links from my presentations at the CMAP Code Camp. This was a really good camp, and there were some great discussions, especially in the Euler session. I really appreciated CMAP inviting me out, and I would be happy to do it again sometime!

1. CakePHP

2. Eulering up your coding skills

I’m writing a Monodroid app that has a main “dashboard” screen and several other “child” screens. Here is how I wire up a button to start up one of the “children” screens:

Note that the static “ClassName” property is just a string, and my lame attempt at not repeating magic strings. The value is “monoStockPortfolio.AddPortfolioActivity”, which can be found in your AndroidManifest.xml.

The “intent” object can be used to pass information to the child screen, which I’ll show in a later post. By using “StartActivityForResult”, the user can click the “back” button found on all Android devices to leave the child screen (with the correct transition). Alternatively, here is how the user can get back without using the back button (i.e. they complete some task on the child screen):

Here I’m saving a new portfolio with a repository, but the key part is the last 3 lines. I’m creating another Intent object, but I’m using it to set a “result” (recall that I used StartActivityForResult to get here). And then I’m calling “Finish” to end the activity.

You can check out the full source code of this project as I go along at GitHub.

Bahaha, sucker! The sensationalist title sucked you in. I don’t hate Ruby at all! In fact, I love Ruby because of the things that it and it’s supporting community have helped to advance:

  • MVC on the web
  • Testing and test-driven development
  • SOLID principles
  • Delivering business value quickly
  • Pressuring other languages and frameworks to keep up

Not to mention some of the most important influences on my career have been Rubyists.

But here’s the thing: I don’t really use Ruby. Honestly, I just don’t really like the language. I’ve been through the Koans, I’ve written some (very helpful) automation scripts for my Linux media server, and some other stuff here and there. But I’ve never really felt comfortable with it. My mind works a certain way, and I don’t think Ruby aligns with it. If you are a Rubyist, that may seem shocking to you, because I read posts all the time that suggest the opposite: Ruby gives you more freedom, Ruby code looks like the way you think, Ruby has gems for everything, Ruby makes you popular and heals all wounds, etc. I’ve just not experienced that.

It’s like hearing all your friends rave about how great a restaurant is, and then actually going there and finding out everything is covered in onions. Sure, it’s great food, if you like onions. But I just can’t eat them. Don’t read too much into that metaphor, because I’m not sure what the “onions” specifically represent.

So, this isn’t to say I hate Ruby (despite the title), or that I’ll never use it. I believe that I should challenge myself and learn new things all the time, including Ruby. I believe in RTRJ. It’s just that Ruby just isn’t at the top of my list, and I probably wouldn’t apply for a position or take on a project that is Ruby focused. I’m just not a Rubyist, plain and simple.