2013-11-25 67 views
0

我有在某些时候它包括在SQL Server中的图像保存数据写在WPF 3.5的应用程序,这是保存数据的部分代码(注意this.pictureImage是一个WPF Image控制): -保存从WPF控件图像到SQL Server数据库

using (SqlCommand command = myConnection.CreateCommand()) 
{ 
    String sqlInsertCommand = "INSERT INTO Info_Id (idNumber, FirstName, Nationality, Image) VALUES (@idNumber, @firstName, @nationality, @image)"; 

    command.CommandText = sqlInsertCommand; 
    command.CommandType = System.Data.CommandType.Text; 

    command.Parameters.AddWithValue("@idNumber", this.cardIdTextBlock.Text); 
    command.Parameters.AddWithValue("@firstName", this.fullNameTextBlock.Text); 
    command.Parameters.AddWithValue("@nationality", this.nationaltyTextBlock.Text); 
    command.Parameters.AddWithValue("@image", this.pictureImage); 

    command.ExecuteNonQuery(); 
} 

我运行此并点击保存到数据库按钮,我得到了下面的错误后。从对象类型System.Windows.Controls.Image存在

没有映射到已知的托管提供

在SQL Server数据库中,我有一个行(图片(图片,NULL))。

请告诉我。谢谢你。

回答

0

您不能保存在数据库中的Image控制。相反,你应该由适当的位图编码器编码在图像控制的Source属性的图像和存储编码缓冲液作为字节数组。

byte[] buffer; 
var bitmap = pictureImage.Source as BitmapSource; 
var encoder = new PngBitmapEncoder(); // or one of the other encoders 
encoder.Frames.Add(BitmapFrame.Create(bitmap)); 

using (var stream = new MemoryStream()) 
{ 
    encoder.Save(stream); 
    buffer = stream.ToArray(); 
} 

// now store buffer in your DB 
+0

那么在SQL Server 2012中怎么会有一个图像数据类型呢?另外,SQL中没有字节数组数据类型,我将如何能够存储它? – darking050

+0

(http://technet.microsoft.com/en-us/library/ms187993.aspx)的[在SQL服务器的图像数据类型]实际上是一个字节数组。链接的文章还说:“避免在新的开发工作中使用这些数据类型,并计划修改当前正在使用它们的应用程序。使用nvarchar(max),varchar(max)和varbinary(max)来代替'。 – Clemens

相关问题