I suppose I should've been more specific. I'd like SqlParameter to automagically deduce that MyClass is a SqlDbType.VarChar (as it does for System.String). It works fine if I manually set the DbType, or cast to a string before adding the value - but I'd like it to be a no-brainer.
For background, the scenario is that I have a custom class for person identifiers used in the domain classes as a sort of strongly typed string. There's an implicit conversion operator on this class to convert to System.String (and an explicit one to convert from string). This works fine when, for instance, assigning to TextBox.Text. Since AddWithValue takes an Object type, there's no compiler error adding instances of MyClass, it simply fails at runtime because it can't figure out the DbType. Obviously, SqlParameter can deduce the DbType of Framework primitives - but is there no hook for adding your own? Am I stuck with, "whenever you add this as a database parameter make sure you explicitly set the DbType or cast to a string first"? --MB > -----Original Message----- > From: Discussion of advanced .NET topics. [mailto:ADVANCED- > [EMAIL PROTECTED] On Behalf Of Frans Bouma > Sent: Thursday, October 04, 2007 2:26 PM > To: [email protected] > Subject: Re: [ADVANCED-DOTNET] SqlParameter Type Mapping > > > Given a custom type, how can you define what value gets passed when > it is > > used as a database parameter? Consider: > > > > public class MyClass { > > public string Value; > > public MyClass(string value) { this.Value = value; } > > } > > > > using (SqlCommand cmd = new SqlCommand()) { > > // I want myClass to be a string when passed to the database! > > cmd.Parameters.AddWithValue("@param", new MyClass("test")); > > } > > > > Right now, I get a "No mapping exists from object type MyClass to a > known > > managed provider native type" - which certainly implies that a > mapping > > *could* exist. I've tried implicit conversion operators to > System.String > > and SqlTypes.SqlString and IConvertible with no luck. > > > > Ideally, it should seamlessly convert to Odbc, OleDb, etc. parameter > > values as well (note that it's the value I want coerced - not > converting > > to an actual SqlParameter). > > > > I would think an attribute, interface or conversion operator would be > the > > trick - but spelunking with Reflector and Google isn't turning > anything > > up. Anyone have any ideas? > > Set parameter.SqlDbType to SqlDbType.VarChar afterwards. > > FB > > > > =================================== > This list is hosted by DevelopMentor(r) http://www.develop.com > > View archives and manage your subscription(s) at > http://discuss.develop.com =================================== This list is hosted by DevelopMentorĀ® http://www.develop.com View archives and manage your subscription(s) at http://discuss.develop.com
