Saturday, March 19, 2011

Custom Content Type with Lookup Column and SPMetal in SharePoint 2010

If you have custom content type in your Visual Studio project that you are going to use to create a List and if that Content Type has a Lookup field that points to another custom content type AND if you try to use SPMetal to create entity classes, you get this error:


Error: The given key was not present in the dictionary.


Now Nowhere in Microsoft documentation it even gives you any clue of this. rather, as per the documentation, it should work flawlessly. 

I came across this article from where I got some clues. So, you have to create a custom parameter XML in order to get it to work. I in any case liked this as if you don't use any parameter file, SPMetal creates a very big, complex entity class and most of the thing in there you wont use. Therefore, using parameterize SPMetal is a good idea to keep code simple.

So here is what I did:


<?xml version="1.0" encoding="utf-8"?>
<Web AccessModifier="Internal" xmlns="http://schemas.microsoft.com/SharePoint/2009/spmetal">
<ContentType Name="Facility"></ContentType>
<ContentType Name="IntakeQuestionaire"></ContentType>
<ExcludeOtherContentTypes></ExcludeOtherContentTypes>
</Web>

Check that you have to use the ExcludeOtherContentTypes element in order to get rid of other content type and you get s simpler code.

Though it has bee a few weeks that I did but I also remember that if you dont use this, and if you in same scenerio, you will get entity class with two entity classes, one for content type and one for list that uses same content type and it names like contenttype1 and list1contenttype1. 

So, as best practice you should always use the Exclude elements and use parameter files for SPMetal.

No comments:

Post a Comment