I need to upload and update file bytes from C# to SQL Server, but I am getting this error in C#:
Microsoft.Data.SqlClient.SqlException: ‘Implicit conversion from data type nvarchar(max) to varbinary(max) is not allowed. Use the CONVERT function to run this query.’
C# code:
public async Task<dynamic> UpdateBulkData(IList<EodUpdateDto> eods)
{
string strTrace = MethodLogger.GetExecutionInfo(MethodBase.GetCurrentMethod());
logger.LogDebug($"Executing {strTrace} with parameter : {JsonSerializer.Serialize(eods)}");
string sqlQuery = $"{StoredProcedures.UPDATE_BULK_EOD} @EODS";
var paramEods = new SqlParameter() { ParameterName = "@EODS", Value = eods.ToDataTable(), SqlDbType = SqlDbType.Structured, TypeName = "EODType" };
await sqlExecutor.ExecuteSqlRawAsync(sqlQuery, [paramEods]);
return true;
}
Code Definition of ToDataTable
public static DataTable ToDataTable<T>(this IList<T> items)
{
DataTable dataTable = new(typeof(T).Name);
//Get all the properties
PropertyInfo[] Props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (PropertyInfo prop in Props)
{
//Defining type of data column gives proper data table
dynamic? type = (prop.PropertyType.IsGenericType && prop.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>) ? Nullable.GetUnderlyingType(prop.PropertyType) : prop.PropertyType);
//Setting column names as Property names
dataTable.Columns.Add(prop.Name, type);
}
if (items != null && items.Count > 0)
{
foreach (T item in items)
{
dynamic values = new object[Props.Length];
for (int i = 0; i < Props.Length; i++)
{
//inserting property values to datatable rows
values[i] = Props[i].GetValue(item, null);
}
dataTable.Rows.Add(values);
}
}
//put a breakpoint here and check datatable
return dataTable;
}
Here value of StoredProcedures.UPDATE_BULK_EOD
is usp_UpdateEODData_U
.
This is the definition of EodUpdateDto
model class:
public class EodUpdateDto
{
public int Id { get; set; }
public string ActionBy { get; set; } = default!;
public bool Accepted { get; set; }
public bool VerifySelfPay { get; set; }
public string Claim { get; set; } = default!;
public bool OnHold { get; set; }
public string HoldReason { get; set; } = default!;
public string AttachFileName { get; set; } = default!;
public string AttachFileType { get; set; } = default!;
public byte[]? AttachFileContent { get; set; } = default!;
}
Here is the design of the SQL Server user-defined table type:
CREATE TYPE [dbo].[EODType] AS TABLE
(
[ID] [int] NULL,
[ActionBy] [varchar](200) NOT NULL,
[Accepted] [bit] NULL,
[VerifySelfPay] [bit] NULL,
[Claim] [varchar](50) NULL,
[OnHold] [bit] NULL,
[HoldReason] [varchar](200) NULL,
[AttachFileName] [varchar](300) NULL,
[AttachFileContent] [varbinary](max) NULL,
[AttachFileType] [varchar](50) NULL
)
This is the stored procedure to which the data is passed:
ALTER PROCEDURE [dbo].[usp_UpdateEODData_U]
@EODS [dbo].[EODType] READONLY
AS
BEGIN
SET NOCOUNT ON;
UPDATE EOD
SET
Accepted = E2.Accepted,
VerifySelfPay = E2.VerifySelfPay,
Claim = E2.Claim,
OnHold = E2.OnHold,
HoldReason = E2.HoldReason,
HoldDate = IIF(E2.HoldReason IS NOT NULL, dbo.GetDateEST(), null),
AttachFileName = E2.AttachFileName,
AttachFileContent = E2.AttachFileContent,
AttachFileType = E2.AttachFileType,
ActionBy = E2.ActionBy
FROM EOD E1
INNER JOIN @EODS E2 ON E1.ID = E2.ID;
END
5
You C# type for AttachFileContent
should be byte[]
because the database column is varbinary
.
But you should reconsider saving binary file content to your database. Your table/db size will balloon, backups and restores will take ages, and it will only continue to grow.
Instead, you should be saving the content somewhere like S3 or on a file system and then retain a link to the location in the database.
Or even better, save the content to a file system with a common naming scheme like the id and then you won’t need to save the location, it will be the same for all with the id inserted. If you need to retain the file name and type you can always save that in the database and then use that to send the data back out.
1