Nezir Zahirović

C# Using Linq to save image to SQL DB

In this post I will show you "How to save Image to a sql db"
1. You need to create a database and table with column of image type:

2.Must add LINQ to SQL Classes into your project (Asp.net C# web project)
3.Drag & Drop your table onto this file

YOU CAN FOUND SAMPLES HOW TO USE LINQ IN ASP.NET
How to Linq & Visual Studio

4 . This is code that you need to inset image :

In Insert Button click event
protected void btnUnos_Click(object sender, EventArgs e)
{
vijesti v = new vijesti();
v.Id = Guid.NewGuid();
v.naslov = txtNaslov.Text;
v.link = txtLink.Text;
v.autor = this.User.Identity.Name;
v.datum = DateTime.Now.ToString();
v.slikaMala = ImgToDb(new FileInfo(Server.MapPath("~//NewsImages//mala.jpg")));
v.slikaSrednja = ImgToDb(new FileInfo(Server.MapPath("~//NewsImages//srednja.jpg")));
con.vijestis.InsertOnSubmit(v);
con.SubmitChanges();
}
private byte[] ImgToDb(FileInfo info)
{
byte[] content = new byte[info.Length];
FileStream imagestream = info.OpenRead();
imagestream.Read(content, 0, content.Length);
imagestream.Close();
return content;
}



Vijesti is my table name:
Image columns are slikaMala,slikaSrednja:

I use here one method ImgToDb
to which I sending a file info as a parameter (that is the image path)

do reading image to a byte[] array and and return as array after that calling
con.vijestis.InsertOnSubmit(v);
con.SubmitChanges();

and image is in ms sql database ;))
SHARE
    Blogger Comment
    Facebook Comment

2 comments: