17.07.2015 Views

The Art of SQL Server FILESTREAM - Red Gate Software

The Art of SQL Server FILESTREAM - Red Gate Software

The Art of SQL Server FILESTREAM - Red Gate Software

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Chapter 4: <strong>FILESTREAM</strong> with Entity Framework and LINQ to <strong>SQL</strong>// Now read the item using SqlFileStream, leveraging// the stored procedure that's mapped as a functionGetSqlFileStreamInfo_Result info =e.GetSqlFileStreamInfo(NewItem.ItemID).ToList()[0];// If the path is NULL, a BLOB file does not exist// and a BLOB must be created firstusing (SqlFileStream fs = new SqlFileStream(info.FilePath, info.Context, FileAccess.Write,FileOptions.WriteThrough, 0L))using (FileStream local = new FileStream("C:\\temp\\Micros<strong>of</strong>tMouse.jpg",FileMode.Open, FileAccess.Read)){local.CopyTo(fs);}tran.Commit();}}finally{// If the connection was opened by this procedure, close itif (OpenedConn) e.Connection.Close();}}}return NewItem.ItemID;Listing 4-8:InsertItem method.This code first creates a new instance <strong>of</strong> the Item class and, for demonstration purposes,assigns values to the ItemNumber, ItemGuid and ItemDescription properties. <strong>The</strong>n,an instance <strong>of</strong> the Entity Framework Object Context (NorthPoleEntities class) iscreated. If the object context does not have an open connection to the database, we openthe connection and keep track <strong>of</strong> the fact that we did so (this means that we can properlyclose it when the method ends).153

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!