Posts
201
Comments
1111
Trackbacks
51
November 2009 Entries
Attaching Modified Entities in EF 4

Lately I’ve been working with EF 4.0 and finding that many of the new features are catching up with the features previously available in other framework like LINQ to SQL.  One example of this is the ability to easily attach objects (for example, disconnected objects that come in from another tier).  For example, imagine you had a web service where a consumer submitted an object to get saved – you’d want to instantiate a new context, attach the incoming entity, and save the object.  In previous versions of EF, this was not a trivial thing to do.  However, this was always quite easy to do in LINQ to SQL by doing this:

   1:  using (var dataContext = new MyDataContext())
   2:  {
   3:      dataContext.Contacts.Attach(someEntity, true);
   4:      dataContext.SubmitChanges();
   5:  }

Notice the second Boolean parameters of the Attach() method – this instructs the context that the entity should treated “as modified” so that an UPDATE command should be issued for that entity when SubmitChanges() gets called (LINQ to SQL also provides an AttachAll() method for collections).  You can now do the same thing in EF 4 like this (I’m using POCO and Code Only here):

   1:  using (var dataContext = new MyDataContext())
   2:  {
   3:      dataContext.Contacts.Attach(contact);
   4:      dataContext.ObjectStateManager.ChangeObjectState(entity, EntityState.Modified);
   5:      dataContext.SaveChanges();
   6:  }

This is a huge leap forward from previous versions of EF but notice that this actually takes one more line of code than its LINQ to SQL counterpart because an explicit call to the ObjectManager’s ChangeObjectState() method must be called. Although this might appear to be a slight inconvenience, it is possible to write a couple of extension methods to simplify this since the ObjectSet’s all have a reference to the parent Context:

   1:  static class ContextExtensions
   2:  {
   3:      public static void AttachAsModified<T>(this ObjectSet<T> objectSet, T entity) where T : class
   4:      {
   5:          objectSet.Attach(entity);
   6:          objectSet.Context.ObjectStateManager.ChangeObjectState(entity, EntityState.Modified);
   7:      }
   8:   
   9:      public static void AttachAllAsModified<T>(this ObjectSet<T> objectSet, IEnumerable<T> entities) where T : class
  10:      {
  11:          foreach (var item in entities)
  12:          {
  13:              objectSet.Attach(item);
  14:              objectSet.Context.ObjectStateManager.ChangeObjectState(item, EntityState.Modified);
  15:          }
  16:      }
  17:  }

This allows you to now save like this:

   1:  using (var dataContext = new MyDataContext())
   2:  {
   3:      dataContext.Contacts.AttachAsModified(contact);
   4:      dataContext.SaveChanges();
   5:  }

This is pretty straight forward and certainly not very complex. However, it is promising that EF is moving in the direction of better enabling these simple scenarios as compared with previous versions.

Posted On Friday, November 27, 2009 10:12 PM | Comments (9)
ASP.NET MVC Application – AlbumCredits.com

Recently my company just released the first version of a new MVC web site: AlbumCredits.com.  This project, led by Oskar Austegard, is was I consider a highly successful real-world implementation of MVC. In a time when most music these days is downloaded, the production and performance engineers, and recording professionals that work on the music don’t always get credit because there is no CD booklet to look through.  Album Credits is almost like a LinkedIn for recording professionals.  From the about page:  AlbumCredits.com is “A fast, easy way to find production and performance credits from more than one million CDs and LPs.”

We leveraged a ton of great technologies during the development of this solution. To name a few:

  • Custom Controller factory based on StructureMap Inversion of Control (IoC) container
  • jQuery for all AJAX needs
  • T4MVC Templates
  • Data Annotations for Validation
  • xVal for client side validation
  • LINQ to SQL with stored procedures (including a few UDFs) for data access
  • SQL Server 2008 with Full Text Search
  • SQL Server Integration Services for the data feed
  • MvcFutures (functionality that will be baked in to MVC2)
  • Numerous custom HTML Helpers
  • Numerous third party jQuery plug ins including:
    • jQuery UI
    • jQuery Tools:
      • Tabs
      • Scrollable
      • Overlay
    • Tablesorter
    • jQuery Form
    • Jcrop
    • jWysiwyg
  • For unit testing – NUnit and NUnitEx
  • For mocking - Moq

Additionally, on the build server we used:

  • Cruise Control .NET
  • MSBuild
  • FxCop
  • StyleCop
  • NUnit

Album Credit starts with a nice AJAX auto-complete search box:

 

The site is then “deep linkable”. Want to see what engineers worked on a particular album?  What other albums did they work on? Which other artists?  You can literally relate any category together in your searching - think Six Degrees of Kevin Bacon but for the music industry.

 

It’s an example of a site that takes a very cool idea and melds it will a solid technical implementation.  Check it out!

Posted On Wednesday, November 18, 2009 10:15 AM | Comments (9)
MVP Lunch at Windows 7 Developer Boot Camp at PDC 09

If you’re planning on being at Windows 7 Developer Boot Camp (already sold out) at PDC 09 next week come check out the “Lunch with the MVPs” scheduled from 12:00-1:15. We will be having several tables where you can come over and have (informal) conversations on a wide range of topics including: MVC, RIA, Silverlight, XNA, LINQ, and more.  I will be leading the table “MVC in the Real World” so come check us out.  Hope to see you there!

Posted On Saturday, November 14, 2009 10:54 AM | Comments (0)
RockNUG Code Samples

Thanks to everyone who attended my LINQ to SQL presentation at RockNUG last night.  The code samples can be downloaded here: LINQ to SQL demo code.

As a point of clarification from last night’s Q&A session after the presentation regarding using LINQ to SQL with true POCO classes that do not even have [Column] mapping attributes, you can have a class like this:

   1:  public class Contact
   2:  {
   3:      public int ID;
   4:      public string FirstName { get; set; }
   5:      public string LastName { get; set; }
   6:      public string Title { get; set; }
   7:  }

If you’re using LINQ to SQL with stored procedures then this class (even without the [Column] attributes) will work just fine.  The one catch is that you can *not* have the class itself decorated with the [Table] attribute which is what happened during the Q&A at the end of last night when someone asked me to show it work without attributes.  I commented the [Column] attribute but did not also comment the [Table] attribute on the class level. If I had also commented out the [Table] attribute, however, then I would have run into this (different issue) because of the “extra” HomeAddress and BusinessAddress properties I added to the partial class (so bear that in mind if you test).

If you watch my blog in the next couple of days (or just subscribe to the rss feed) I’ll put up a post dedicated strictly to the various mapping options you have with LINQ to SQL and downloadable code examples of each since the only mapping I showed last night was the attributed-based mapping (e.g., mapping with attributes, mapping with XML, mapping differences with auto-generated SQL vs. stored proces, mapping with true POCO, etc.).  Thanks!

Posted On Thursday, November 12, 2009 1:11 PM | Comments (0)
LINQ to SQL Again??

Tomorrow night I’ll be at RockNUG presenting LINQ to SQL. Yes, LINQ to SQL. Again. In the last 2 years I have presented LINQ to SQL numerous times at various user groups and code camps. Why do I keep getting asked to present LINQ to SQL? Isn’t LINQ to SQL dead? Answer: No.  LINQ to SQL is not dead!

This confusion all started back in October 2008 with a seemingly innocuous post on the ADO.NET team blog discussing the emphasis that Microsoft was going to put into the Entity Framework going forward.  The developer community was immediately up in arms about this post for a variety of reasons.  First, many developers and companies had already made a significant investment in developing with LINQ to SQL.  Secondly, LINQ to SQL is great so why de-emphasize it?  Third, the Entity Framework has had its share of challenges getting acceptance in the development community (and I’m being charitable) so the thought of replacing something “good” with something “not as good” was not met with enthusiasm.

This led to a “clarification message” by the ADO.NET team a few days later in which they clearly state: “LINQ to SQL is not dead.” This post may have been a somewhat weak defense of LINQ to SQL but the message was clear nonetheless. We’ve also seen others from Microsoft strongly advocate LINQ to SQL.  For example, in this MVC presentation at MIX 09, Scott Hanselman states he’s using LINQ to SQL in the demo “because it’s awesome and it’s not dead.” This all leads to a somewhat confusing state of affairs because we find ourselves relying on quotes from a respected Microsoft guru like Scott Hanselman and others in an attempt to translate Microsoft’s marketing approach for their latest data access strategy. After all, one of the longest running jokes is that the last thing Microsoft needs is yet another data access framework.

So how do we make this pragmatic decision for ourselves when deciding on a data access strategy/framework? Although there are numerous data access choices, the top three frameworks that are typically examined are: 1) LINQ to SQL, 2) NHibernate, and 3) the Entity Framework (EF).

The Entity Framework vNext that will be released after .NET 4.0 looks very promising.  Model first, POCO code only, foreign key relationships, and more make me enthusiastic to give EF another run next year.  But…that’s next year. If you’re starting development on a new application today, you might think twice.

NHibernate is a great framework. No dispute there. On it’s own it’s solid but then when you add features such as Fluent NHibernate and LINQ to NHibernate it’s becomes an extremely compelling choice. However, there is a steeper learning curve with NHibernate as compared to some other frameworks such as LINQ to SQL.  Additionally, some organizations (unfortunately) have policies against using open source software which disqualifies NHibernate in those environments.

Then you’ve got trusty ol’ LINQ to SQL. In the last year, LINQ to SQL has continued to provide a solid data access choice. I strongly agree with the numerous points that Ian Cooper made in this post showing support for LINQ to SQL. In short, there are numerous reasons to learn and use LINQ to SQL. Among them:

  • LINQ to SQL is a stable release and has withstood the test for 2 years now. You don’t have to wait for the next release (like EF) – you can use it *now*.
  • Open source is not always an option (depending on your environment). LINQ to SQL is good to go here.
  • The skills you learn in LINQ to SQL are transferrable.  In other words, if you learn LINQ to SQL now and later decide to switch to EF next year, you won’t be starting from scratch. Your knowledge will be transferrable.
  • There are also some cool OSS projects for LINQ to SQL such as Fluent LINQ to SQL.

And finally, LINQ to SQL is just flat out *good*. While it may not be perfect (no framework is) the designers of LINQ to SQL inside Microsoft really got far more right than wrong when creating LINQ to SQL. You can use it with a RAD designer or you can hand code all your classes.  You can use it with C# attributes for mapping or external XML mapping files (or fluent mapping with OSS libraries). You can use it with auto-generated SQL or stored procedures. You can use it with POCO classes. You can use it in an N-Tier application without having to worry about serialization of your entities. It supports lazy loading or eager loading. The list goes on.

Having implemented numerous production applications with LINQ to SQL, I’m happy with it. But I’ll continue to learn more about it and other data access technologies as well as they come out.

If you’re in Rockville tomorrow night and have a desire to start learning LINQ to SQL, come on out!

Posted On Tuesday, November 10, 2009 9:26 PM | Comments (4)
ASP.NET MVC in Action Review

In an effort to continually improve as a developer, one of the things I do is read lots of books. Recently I read ASP.NET MVC in Action by Jeffrey Palermo, Ben Scheirman, and Jimmy Bogard. In short, I consider this a “must read” for anyone who is serious about developing with the ASP.NET MVC framework.

I’ve heard some people say that this should not be your first MVC book because it is more advanced than other MVC books available.  While I can understand that logic to a degree, I think it would be more accurate to say that if you’re literally brand new to MVC, this might not be the best “introductory” book.  However, if I could only own one book on MVC, this book would be it. There are two common themes from this book that I really enjoyed. First, the authors base their content on “real world” concepts rather than just explaining every topic in a mechanical way. This gives a great real world context throughout the book.  Secondly, the authors are not afraid to be “opinionated” in their recommended best practices for the MVC framework. These are aspects that are lacking in many technical books.

The book starts out with a nice introduction to MVC (and it’s not too advanced to follow in the least). One of the things I really liked about this first chapter is that it spent some time discussing the history of web development which gave great context to where and how ASP.NET MVC fits into the discussion. This included many of the reasons as to *why* we have the MVC framework to begin with. The very next chapter dives into the Model of MVC and does a great job explaining the differences between domain models and presentation or view models.  Philosophically, I really agree with their concepts around view models and I have referenced some of them before on this blog. Understanding these view model concepts is essential to building mature MVC applications.

The books then dives into Controllers. The aspect I enjoyed most about this was the emphasis on unit testing. This included mocking and best practices for dependencies. The Controllers chapter ended with a discussion of action filters which was decent but I would have liked if the discussion of action filters had been expanded a little. The Views chapter provided great content covering validation, custom html helpers, partial views, and more. I didn’t find the Views chapter to be very advanced at all – rather, it provided a solid foundation for the type of information developers should know when building views.

I really appreciated the chapter on Routing. It discussed designing the routing topology of your application up front which is often overlooked. It also discussed REST best practices. The examples of Routing constraints were one of the strongest parts of the chapter and they are an area that I’ve observed is often overlooked in MVC applications. My favorite part of the Routing chapter was unit testing routes with the very cool route testing extensions available in the MvcContrib project which makes unit testing routes trivial. For example, it showed how you can test a route in one simple line of code like this: "~/boiseCodeCamp/edit".ShouldMapTo<ConferenceController>(x => x.Edit("boiseCodeCamp"));

Towards the end of the book there was a chapter dedicated to exploring (for the sake of contrasting and understanding historical context) MonoRail and Ruby of Rails.  I always find the comparisons between Ruby on Rails and MVC very interesting and that was true in this book as well.  However, I didn’t find myself as engaged in the MonoRail discussion and I didn’t think it added as much to the book as the Ruby on Rails section.

Probably the best chapter in the book was the one dedicated to Best Practices. Once again the authors were not afraid to be opinionated in their recommendations and this was based on “real world” experience with the framework (for which there is no substitute). One example I really liked from this section was the advocating of the RenderAction() method. This method has not been without its share of controversy because there are some “purists” that believe the existence of this method violates the tenets of the MVC framework because this means the view has some “knowledge” of the controllers. However, the authors point out (correctly, in my opinion) that the method allows for a much more elegant implementation in many cases that is a very pragmatic choice that actually leads to *better* separation of concerns in many instances since the partial gets its own controller.

Learning the mechanics of MVC is important. But even more important is learning best practices and how you can extend the MVC framework to suit your needs when the situation requires it. In my opinion, this is the best book I’ve read that can help get you to that goal.

Posted On Saturday, November 7, 2009 9:37 PM | Comments (1)
CMAP Code Camp – MVC in the Real World Code Samples and Extra Resources

Thanks to everyone who attended my “MVC in the Real World” presentation at CMAP Code Camp today.  The code as well as the PowerPoint can be downloaded here:

MVC in the Real World Download

I also had a few other requests during the talk.  First, I had a request to post the code as it looked at the very beginning of my talk before I modified anything.  You’ll find that link on the download page above as well (file name: PersonalInfoManager-ReadlWorldMVC-Begin.zip). 

Second, I was asked about a couple of the tools I was using.  You can see the links for all the tools I use (almost all free) on my Developer Tools and Utilities page.

Third, I had a request to post some links that discussed some of the Unit Testing best practices. Brad Wilson (one of the primary developers of xUnit) co-authored this excellent article: Effective Unit Testing. I also really like this slide deck which he also published: Lessons Learned in Programmer Testing. Roy Osherove also has a great post on Naming Standards for Unit Tests. Finally, I love this article by Jeremy Miller in MSDN magazine entitled Designing for Testability. One of his article’s major premises is that “testable” code typically will naturally result in “well designed” code – a concept that I’m a huge fan of.

Posted On Saturday, November 7, 2009 8:10 PM | Comments (10)
CMAP C# 4.0 Presentation – Code Samples

Thanks to everyone who attended my C# 4.0 New Languages Features presentation at CMAP last night.  Both the code and PowerPoint are available for download.

C# 4.0 New Language Features Download

After the presentation, I had a few people ask me about some of tools I was using.  They can all be found on my Developer Tools and Utilities page. To create my snippets, I’ve been using a tool called Snippy for years (link included on Developer Tools page).  However, lately I’ve also been using Snippet Designer which is a Visual Studio add-in that is also quite good.

Posted On Wednesday, November 4, 2009 1:02 PM | Comments (1)
CMAP Presentations this week

I’ll be giving a presentation on C# 4.0 New Language Features this Tuesday at the CMAP Main Meeting.

Also I’ll be presenting MVC in the Real World this Saturday at CMAP Code Camp.

Hope to see you there!

Posted On Sunday, November 1, 2009 8:22 PM | Comments (0)

View Steve Michelotti's profile on LinkedIn

profile for Steve Michelotti at Stack Overflow, Q&A for professional and enthusiast programmers




Google My Blog

Tag Cloud