Monday, June 2, 2008

Mapping varchar(max) - using micorosoft application data blocks (No mapping exists from DbType .. to a known SqlDbType ....)

I have been happily using application blocks for various tasks in my project and the data blocks was one of them. I had code like this which worked fine ..

Dim lDatabase As Database = DatabaseFactory.CreateDatabase()
Dim lCommand As DbCommand = lDatabase.GetStoredProcCommand("dbo.pr_service_WriteLog")
lCommand.CommandType = CommandType.StoredProcedure
'-- add the parameters
lDatabase.AddInParameter(lCommand, "@CreatedOn", SqlDbType.DateTime, DateTime.Now)
'-- add the error type
lDatabase.AddInParameter(lCommand, "@LogType", SqlDbType.VarChar, EntryType.ToString)
lDatabase.AddInParameter(lCommand, "@LogType", SqlDbType.VarChar, lLogBase.Type.ToString)
'-- add the message
lDatabase.AddInParameter(lCommand, "@LogMessage", SqlDbType.VarChar, lLogBase.Message)

lDatabase.ExecuteNonQuery(lCommand)

This worked fine for quite sometime till I had a new requirement to write a SP which had to insert into a table a fields with the data type defined as varchar(max). To apss this new type from the UI to SP I tried
lDatabase.AddInParameter(lCommand, "@NewParam", SqlDbType.text, MyValue)

It gave the error "No mapping exists from DbType UInt16 to a known SqlDbType." ..
So I tried various other types like Nvarchar etc etc .. but all failed .. Then I started reading about the data types supported by the data block and I came to realise that instead of using SQLDbType, i could use DBtype directly. So I tried DBtype.string and it worked !!!

Hope this helps someone who might get stuck in a similar area ....