Monday, 30 September 2013

CRM - Lookup field name vs relationship field name

Today I thought I'd discuss a little gotcha in CRM 2011 that I'm amazed remained as a "feature" for so long! Have you ever seen "foreign key" fields in a CRM system and noticed that some are called "new_ContactId" where as others are called "new_Contact"? There's a fairly simple reason this occurs, it's basically a result of the developer/consultants preference when creating fields. Let's take a quick look at each method.

Old School - Creating relationships

If, like me, you have progressed from CRM 4 or earlier you generally create relationships between entities using the same method as always existed. You open up the entity customizations, navigate to 1:N or N:1 relationships and you get this screen:


You will notice I have highlighted what it will create the field as in the background: "new_ContactId". Most people comfortable with CRM throughout many versions will be familiar with this convention of creating fields.

New School - Lookups

Since CRM 2011 we now have a second way to create relationships. Rather than going via the relationship links on an entity simply pick the entity where you want the "foreign key" field to reside. In our example this is on the entity called "Custom Method". Navigate to the list of fields and simply add a new lookup field. Like this:


This time you'll notice I have highlighted the field name "new_Contact". We're missing the "Id" part!

Old School or New School?

I guess this is the question, which do you prefer? Personally, I prefer the new field naming convention for one simple reason. As CRM developers you don't really have your head in tables and SQL as much any more. Instead you're using plugins and Entities / Entity References. So generally in a plugin you'll use code like this:

var contactReference = (EntityReference)customMethod["new_ContactId"];

This "Id" always bugged me, because of this simple fact - it's not an Id in code, it's a reference. So if you just wanted the "Id" in code you use this:

var contactId = ((EntityReference)customMethod["new_ContactId"]).Id;

Which I don't like, because you're repeating the abbreviation "Id". In my opinion this kind of violates "DRY" so I will avoid it if at all possible. Using the new school way it looks cleaner without this repetition:

var contactId = ((EntityReference)customMethod["new_Contact"]).Id;

So whenever I create a field using the relationship convention I will manually remove the "Id" part.

No comments:

Post a Comment