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>As we have already discussed, access to <strong>FILESTREAM</strong> data must occur in the context <strong>of</strong>a <strong>SQL</strong> <strong>Server</strong> transaction, so we start a transaction using the BeginTransaction()method on the Connection object associated with the object context. As part <strong>of</strong> thattransaction, we add the newly created Item object to the object context and save thechanges to the database.Saving the changes to the database causes the ItemID property <strong>of</strong> the NewItem objectto be set to the value assigned by the database engine (recall the mapping we modifiedearlier). We use this value as the parameter for the GetSqlFileStreamInfo method.Even though we know that the GetSqlFileStreamInfo method can only return asingle object instance, because the SELECT statement in the stored procedure filters bythe table's primary key (ItemID), the framework doesn't have that knowledge and willreturn a set <strong>of</strong> GetSqlFileStreamInfo_Result objects. We will simply take the firstand only item in that list.Using the values in the GetSqlFileStreamInfo_Result object, we can create a newSqlFileStream instance for write access. From the local file system, we open a sampleimage file using standard .NET file I/O APIs. We then copy the bytes from the local file tothe SqlFileStream.Finally, we commit the transaction and, if we opened it, close the database connection.Retrieving information from the databaseTo end this lab, we are going to add some code that can retrieve a specific item (row) fromthe database. We will use the Entity Framework object relational mapping to retrieve therelational data, but use streaming I/O access to work with the <strong>FILESTREAM</strong> data.Listing 4-9 shows the ReadItem method to be added to the Program class. This coderequires that you import two namespaces in your code file: System.Data.SqlTypesand System.IO.154

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

Saved successfully!

Ooh no, something went wrong!