views:

46

answers:

2

Do buddy classes only work for dataannotations, or for any attribute? I've been trying to attach a ColumnAttribute to a field in my buddy class, but it appears that it doesn't get processed in the original class. The two classes are linked via MetadataType.

A: 

My answer is not DataAnnotations specific, this is a globabl answer of how to associate type descriptors.

Create a subclass of TypeDescriptionProvider that describes the relation of the classes (you can skip this part in some cases where u can use an existing descriptor such as AssociatedMetadataTypeTypeDescriptionProvider).

Then use TypeDescriptor.AddProvider or TypeDescriptor.AddProviderTransparent to dynamically attach them runtime.

My suggestion is have a service that has a list of flagged types, and run all the types thru it (on demand, so the performance cost is spread at the application running time), and when a type is processed, add the type to the list, and next time this type requests, you know it's in the list.

Shimmy
A: 

The buddy class technique is not anything special to DataAnnotations. However, it only works if the reflection code you're using does something with the MetadataType attribute. So, ASP.NET MVC is an example of a codebase that handles the buddy class concept, while Linq-to-sql does not. So, at the moment you're stuck if you want to use buddy classes to add a ColumnAttribute. However, if you really need to get fancy, Linq-to-SQL will take an XML document with the mappings instead of using attributes. You could use that to build your mappings as an alternative for the instances where you might have used a buddy class.

If you need to get really, really fancy, go ahead and make your buddy class and then write your own buddy-class-aware reflection handler against your Linq attribute decorated classes and construct XML mapping documents from that for your DataContext needs. You could probably do that in under 50 lines of code.

mattmc3