tags:

views:

174

answers:

2

I have a custom type that I created, which should be persisted in a database (in this case, SQL server) as a guid (though this question is just as valid for an object that could be stored as a string, integer, etc).

When I pass this type as a parameter to a DbCommand object, I get an exception:

ArgumentException: No mapping exists from object type [...] to a known managed provider native type.

I have CType operators on the class that allow implicit conversion to a string, or a guid, but .NET doesn't use these since it doesn't know it should convert the type.

Is there a way to add a type to the internal mapping, or otherwise tell .NET how to store my custom type in the database?

I obviously can convert the type myself when passing it to the .NET stuff, but I'd like this to happen automatically, like it does for most of the built-in types.


I've tried to implement a TypeConverter class for my type (inherits from TypeConverter, overrides CanConvertFrom, CanConvertTo, ConvertFrom, ConvertTo, IsValid, and added the System.ComponentModel.TypeConverter attribute to my class), but this still doesn't work.

I'm assuming it's missing a piece telling .NET what type to convert to when storing the value in the database.


My workaround for this, for now, is that I intercept the list of parameters, before I pass them to SQL server, and have a method that changes my custom type into a guid. This is dirty, but it does work for now, but I still think this question is unanswered.

A: 

Here are some links to Type Converters in .Net

http://msdn.microsoft.com/en-us/library/yy580hbd.aspx

http://msdn.microsoft.com/en-us/library/ayybcxe5.aspx

Min
I followed the instructions and implemented a typeconverter class (overriding CanConvertFrom, CanConvertTo, ConvertFrom, ConvertTo, IsValid), and adding the TypeConverterAttribute to my custom type class, but no go - I still get the same error.
gregmac
+1  A: 

According to http://stackoverflow.com/questions/767072/how-should-i-pass-a-user-defined-type-to-sqlparametercollection-addwithvalue, it's not possible. I've looked at the GetMetaTypeFromValue method as well, and it looks like all the mapping is in fact hardcoded in the framework, thus no user-defined mapping is possible.

How annoying, it would be really useful to have an attribute that defines mapping for a given type.

gregmac