Dane Morgridge

  Home  |   Contact  |   Syndication    |   Login
  26 Posts | 0 Stories | 19 Comments | 0 Trackbacks

News

I'll be speaking at the Central Penn Code Camp on Dec 5.

Twitter












Archives

Post Categories

Wednesday, January 27, 2010 #

The second installment of the Community Megaphone Podcast is now up and you can view it at http://www.communitymegaphonepodcast.com.  Our guest for Show #2 is Joel Cochran and we talked primarily about Blend and WPF:

Originally an AS/400 RPG Programmer, Joel is a former Contributing Editor for ITJungle.com (originally MidrangeServer.com) and has taught various programming languages and Internet technologies at Blue Ridge Community College. He has been developing in C# full time since 2003 and currently devotes most of his efforts to Blend and WPF. A frequent speaker at User Groups and Code Camps, he enjoys teaching and writing about .NET and other technologies, which he happily shares on his blog at http://www.developingfor.net. Joel has served as the Director of Operations for Stonewall Technologies, Inc., in Staunton, VA, since 2000.

Audio: http://www.communitymegaphonepodcast.com/Content/Audio/Show-2-Joel-Cochran.mp3
Show Url: http://www.communitymegaphonepodcast.com/Show/2/Joel-Cochran
Rss: http://feed.communitymegaphonepodcast.com/cm-podcast


Tuesday, January 19, 2010 #

I'll be giving my "Getting to Know the Entity Framework" presentation at this month's BaltoMSDN meeting tomorrow.  If you're in the Baltimore area and are interested in Entity Framework, come out to the meeting.  All the details at http://www.baltomdsn.com

Location:
System Source
338 Clubhouse Road
Hunt Valley, MD 21031
http://www.baltomsdn.com


Wednesday, January 13, 2010 #

I am very excited to announce the Community Megaphone Podcast.  It is a new podcast hosted by myself and G. Andrew Duthie (aka devhammer) that focuses on community as well as technology.  The guests will be developers and speakers that you would find at your local user group or code camp.  Our hope is that this podcast will help you, as a developer, to learn more about speakers in your area and encourage you to visit your local user groups or code camps.  The podcast is part of Community Megaphone and is a site dedicated to making it easier for software developers and IT professionals to promote and discover local community events.  Community events are a huge help to many developers and we want to give you another resource to help you find the community events that will help you the most.

The podcast audio and rss links can be found at the Community Megaphone site as well as the podcast site: http://www.communitymegaphonepodcast.com.  If you have any questions or comments or would like to recommend a guest, fill out the contact form on the podcast website.

The guest for our first show is Kevin Griffin.  Kevin is a .NET Developer for Antech Systems, located in Chesapeake, VA. He’s the leader of the Hampton Roads .NET Users Group. Often, he can be found speaking at or attending other local user group meetings or code camps. He enjoys working with new technology, and consistently works on being a better developer and building the best software he can.

Kevin's blog is http://www.kevgriffin.com and he can be found on twitter @1kevgriff.

Check it out and make sure you get to your next community event.


Saturday, January 09, 2010 #

Persistence ignorance is, I believe, one of the most important features of an ORM tool and it is coming with Entity Framework 4 and Visual Studio 2010.  When your classes are persistence ignorant, they don't know anything about the data layer they are attached to and carry no dependency to said data layer.  Any application where your data will be passed between layers, like in a web service or web application, will greatly benefit from an ignorant set of data classes.  This was possible with Entity Framework 1, but you had to write your own custom classes and then also manage a translation layer to convert from Entity Framework classes to POCO (Plain Old CLR Object) classes.  While this does work, it requires additional code to be written that could be avoided.

Entity Framework 4 addresses this problem by allowing you to create a custom data context that interacts directly with the custom POCO objects.  Instead of needing a translation layer, the context can return your POCO objects in queries and also save those same objects, just like the standard context would with the normal Entity Framework objects.

To check out this new feature you will need Visual Studio 2010 beta 2 and the latest feature CTP.  The feature CTP contains a T4 template that will make working with POCO much easier.  If you want to work with POCO but don't download the CTP, you can still do so, but you will need to craft the POCO classes by hand instead of using the T4 template to do it for you.  I think the T4 template is a smoother way to do things so I would recommend getting the CTP.  Hopefully the T4 templates will be included with the final release of VS2010, I am assuming that they will be.

To get started, you need to have a data model with entities already in your project.  If you don't have a model already in your project, take a moment to check out my post on Model First Development. I will use the same database in this post so my model looks like this:

 EF4Poco_1
You can at this point write queries against the model like normal so the following code will compile and run with out issue:

   1: using (EFDemoEntities db = new EFDemoEntities())
   2: {
   3:     var people = db.Person.ToList();
   4: }


This is of course is using the base code generation template to use Entity Framework objects.  To start using POCO, we can change the code generation template by right clicking on the model and selecting "Add Code Generation Item":

image

This will open a dialog to add a new item.  Under "Installed Templates", you will need to select the "Code" section as the "Data" section is probably selected by default.  Once you see the following options, select the "EntityFramework POCO Code Generator"


 image

Now my solution has the following files:

image


The Model1.Context.tt and Model1.Types.tt files are the actual T4 templates used to generate the code. You can see that under the Model1.Context.tt there is a new data context class and under the Model1.Types.tt there are class files for all of your entities in your model. Also in the types is the Model1.Types.cs file.  This file contains some code to make the collections work better with the Entity Framework, but don't carry any dependency on the Entity Framework. 

If you build the project right now, you will very likely get 3 errors:

image 

All three of these errors are due to an error in the template surrounding the old option for deferred loading and the new option for lazy loading.  The template currently generates the context constructors as follows:

   1: public EFDemoEntities()
   2:     : base(ConnectionString, ContainerName)
   3: {
   4:     ContextOptions.DeferredLoadingEnabled = true;
   5: }
   6:  
   7: public EFDemoEntities(string connectionString)
   8:     : base(connectionString, ContainerName)
   9: {
  10:     ContextOptions.DeferredLoadingEnabled = true;
  11: }
  12:  
  13: public EFDemoEntities(EntityConnection connection)
  14:     : base(connection, ContainerName)
  15: {
  16:     ContextOptions.DeferredLoadingEnabled = true;
  17: }


The easiest way to fix this is to change the template.  Search the Model1.Context.tt file for DeferredLoadingEnabled = true and change it to LazyLoadingEnabled = true.  Saving the T4 template will re-generate the context file producing the following constructors:


   1: public EFDemoEntities()
   2:     : base(ConnectionString, ContainerName)
   3: {
   4:     ContextOptions.LazyLoadingEnabled = true;
   5: }
   6:  
   7: public EFDemoEntities(string connectionString)
   8:     : base(connectionString, ContainerName)
   9: {
  10:     ContextOptions.LazyLoadingEnabled = true;
  11: }
  12:  
  13: public EFDemoEntities(EntityConnection connection)
  14:     : base(connection, ContainerName)
  15: {
  16:     ContextOptions.LazyLoadingEnabled = true;
  17: }


The project will now compile without errors, including the data query.  The T4 template not only generates POCO objects but changes the entire code generation template so the original classes no longer exist.  This is helpful because you can start with the standard code generation and then change to POCO at a later date if you wish.  When using POCO and the template, you can still use all of the new features like lazy loading just as you can with the standard Entity Framework classes.

So as, you can see, switching your Entity Framework project to use POCO is very simple and doesn't require you to make any query changes to leverage it.  If you are not using persistent ignorant classes with Entity Framework, it's something you should take a serious look at.


Wednesday, December 16, 2009 #

I'll be speaking tonight at the Philly .NET user group on the Entity Framework, if your in Philly and are at all interested in checking out the Entity Framework, come on out.  Details: http://www.phillydotnet.org/Default.aspx?tabid=809


Saturday, December 05, 2009 #

I was giving an Entity Framework talk in Harrisburg, PA at the Central Penn Code Camp earlier today and afterwards I was talking with one of the developers that attended my session. He was a little hesitant to use Entity Framework because he didn't want to use it solely as his data layer.  I explained that you don't have to use it directly as your data layer but could add another layer of abstraction.  This is actually how I use Entity Framework almost exclusively.  In short, how I do this is I build a set of classes that do all the interaction with the Entity Framework context.  I use these classes to wrap my Entity Framework calls so that I don't use my data context directly within say a mvc controller.  Below is a sample of how I do this:

 

   1: public class ContactAdministration
   2: {
   3:     public List<Person> GetAllPeople()
   4:     {
   5:         using (ContactEntitiesContainer db = new ContactEntitiesContainer())
   6:         {
   7:             return db.Person.ToList<Person>();
   8:         }
   9:     }
  10:  
  11:     public Person GetPerson(int personId)
  12:     {
  13:         using (ContactEntitiesContainer db = new ContactEntitiesContainer())
  14:         {
  15:             return db.Person.Where(p => p.PersonId == personId).FirstOrDefault<Person>();
  16:         }
  17:     }
  18: }

 

This is a basic example of how I would implement a data layer class that wraps the Entity Framework.  Then when I need to access data from with in my application I can simply so some calls like:

 

   1: ContactAdministration contactAdmin = new ContactAdministration();
   2:  
   3: List<Person> people = contactAdmin.GetAllPeople();
   4:  
   5: Person p = contactAdmin.GetPerson(1);

 

This method has quite a few advantages.  First off, it allows for more persistence ignorance in your data layer (especially if you are using EF4 POCO classes) and it also give you a greater separation of concerns. It also gives you simple code reuse since you will likely call some of the methods in more than once place in your application.

So basically what we have it a method where you can use Entity Framework as your data access technology, but not necessarily as your direct data layer.  It requires you to write a little more code up front, but less down the road and makes the code more maintainable.


Wednesday, December 02, 2009 #

I am a huge fan of code reuse, as any good developer would be, but there it the tendency at times to write "near-duplicated" code.  Near-duplicated code is when you have a function, like a database save or delete, that is rewritten multiple times, but with small, but seemingly important differences.  There are many times where those "seemingly important" differences can be easily abstracted away. 

For example, I can write a Save method in the Entity Framework as follows:

 

   1: public Person SavePerson(Person person)
   2: {
   3:     using (EFDemoEntities db = new EFDemoEntities())
   4:     {
   5:         Person entity = db.Person.Where(p => p.PersonId == person.PersonId).FirstOrDefault();
   6:         if (entity == null)
   7:         {
   8:             db.AddObject("Person", person);
   9:         }
  10:         else
  11:         {
  12:             db.ApplyPropertyChanges("Person", person);
  13:         }
  14:         db.SaveChanges();
  15:         db.Refresh(System.Data.Objects.RefreshMode.StoreWins, person);
  16:         return person;
  17:     }
  18: }

 

Here I have a method that will take a Person entity and save it.  If first does a lookup to see if the person already exists on line 5.  If it does, the entity will be loaded into the context and line 12 will apply the changes from "person" to "entity".  This is done "magically" because of the way Entity Framework stores key data within the object context.  If the entity doesn't exist, it will be added on line 8 and then the save changes call on line 14 will commit it to the database.  I have this method also returning the entity passed in because there are quite a few times where I need to have the ability to pull back an inserted entity and start using it right away. 

I can easily write several methods to do the same thing for each entity type that I will be saving, or I can build a reusable method that I only have to write once.  By making a couple of small changes, I have a method that will work with any entity in the model:

 

   1: public object Save(string entitySetName, object entity)
   2: {
   3:     using (EFDemoEntities db = new EFDemoEntities())
   4:     {
   5:         System.Data.EntityKey key = db.CreateEntityKey(entitySetName, entity);
   6:         if (int.Parse(key.EntityKeyValues.First().Value.ToString()) > 0)
   7:         {
   8:             object obj = db.GetObjectByKey(key);
   9:             db.ApplyPropertyChanges(entitySetName, entity);
  10:         }
  11:         else
  12:         {
  13:             db.AddObject(entitySetName, entity);
  14:         }
  15:         db.SaveChanges();
  16:         db.Refresh(System.Data.Objects.RefreshMode.StoreWins, entity);
  17:         return entity;
  18:     }
  19: }

 

The "Save" method does the same thing as the "SavePerson" method, except that it can be used for any entity associated with the EFDemoEntities context.  There are a few differences between the two methods that make this possible:

Line 1 is changed to also take in the EntitySetName which was hard coded as a string in the first method. This is passed to the ApplyPropertyChanges and AddObject methods instead of hard coding a string.

Line 5 is creating an entity key from the passed in entity.  This has to be done because the key will sometimes be null depending on where the entity came from.  The EntityKey is used to fetch the current object in the database for comparison. which is done in line 8.  This function is built to expect that there will be a single key on the entity and that it will be an int.  This if statement would need to be modified to check for different keys depending on your model.

So as you see we have a method now that can be called when ever we need to save an entity object instead of having to write a new save method for each entity that we need to be able to save.  While this method may not be useable in every scenario, it should cover most of your saving needs.  You could also abstract this out a level further and pass in the context as a parameter so that the same method would work across multiple data contexts.

Note:  The code above is written against v1 of the Entity Framework.  To use this with Entity Framework 4, you will need to change line 9 from ApplyPropertyChanges to ApplyCurrentValues.  With that change, I have been using this method with Entity Framework 4 POCO classes so this method ports easily between versions.

This same concept can easily be applied to deletes as well.


Monday, November 23, 2009 #

I will be presenting on the Entity Framework in Harrisburg, PA at the Central Penn Code Camp on Dec 5th, 2009.  Details can be found at the code camp site:

http://centralpenn.web121.discountasp.net/home/CodeCamp2009/2009Schedule/tabid/84/Default.aspx


Thursday, November 19, 2009 #

I just got done with my NotAtPdc Session On "Getting to Know the Entity Framework".  Of course like a good live presentation, my demo broke.  The problem was in the connection string.  When I did the model first development, I named the model something different for some reason and that caused the connection string to be out of sync in the actual application.  Someone had mentioned that was the problem in the chat, but I didn't see it until after the demo was over.  So, in case anyone else happens to run into this error down the road, be sure your connection string in the app that is using your data model is up to date.  And thanks to the person who mentioned that.  (I don't have the chat log in front of me so I don't have your name or I'd give you credit)

Thanks to all that attended my session and you can download the demo code (that actually works) here.


Wednesday, November 18, 2009 #

I am doing my "Getting to the Entity Framework" talk at NotAtPDC this year.  It will be a virtual event via live meeting and will start at 1:30 CST tomorrow, November 19, 2009.  You can get all the details at the NotAtPDC site: http://www.notatpdc.com/Schedule/Detail/27

I will also be doing a quick 15 minute quick start on Entity Framework tomorrow night at the monthly Philly.Net metting with a discussion panel to follow: http://phillydotnet.org/

If you are all interested in checking out what Entity Framework has to offer, both in it's current state and upcoming release, checkout my NotAtPDC session tomorrow. 

I also have several blog posts in the works on some new features coming in Entity Framework 4 and I'll start posting them with in the next few days.