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

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Chapter 4: <strong>FILESTREAM</strong> with Entity Framework and LINQ to <strong>SQL</strong>static void ReadItem(int itemId){// Obtain info about the objectusing (NorthPoleEntities e = new NorthPoleEntities()){// This does not cause the BLOB to be read with T-<strong>SQL</strong> as long as// the BLOB column is in a different object,// or excluded from the model altogether (preferred)Item i = e.Items.SingleOrDefault(itm => itm.ItemID == itemId);if (i != null){Console.WriteLine("Read Item GUID: {0}", i.ItemGuid.ToString());bool OpenedConn = false;try{// Ensure the connection is open before// attempting to start a transaction// NOTE: connection is probably closedif (e.Connection.State != System.Data.ConnectionState.Open){e.Connection.Open();OpenedConn = true;}// <strong>The</strong>re are also ways to use// Systems.Transactions.TransactionScope// to enlist in an existing transaction// at the business logic level if desiredusing (System.Data.Common.DbTransaction tran =e.Connection.BeginTransaction()){// Now read the item using SqlFileStream,// leveraging the stored// procedure that's mapped as a functionGetSqlFileStreamInfo_Result info =e.GetSqlFileStreamInfo(i.ItemID).ToList()[0];// If there is a BLOB, there is a file pathif (!string.IsNullOrEmpty(info.FilePath) &&info.Size > 0){using (MemoryStream ms = new MemoryStream())155

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

Saved successfully!

Ooh no, something went wrong!