Visual Studio 2008 SP1: ADO.Net Entity Framework support for FILESTREAM

12 במאי 2008

אין תגובות

Visual Studio 2008 SP1: ADO.Net Entity Framework support for FILESTREAM


ADO.Net Entity Framework support for FILESTREAM In Visual Studio 2008 and .Net Framework 3.5 SP1, not only that LINQ to SQL supports SQL Sever 2008 FILESTREAM, but also the ADO.Net Entity Framework supports FILESTREAM as well.


Using the File Management Schema from my SQL Server 2008 FILESTREAM post, I created a simple .net application that uses Entity Framework in order to access the file contents.


Just a reminder of how the Files table looks like:



CREATE TABLE [dbo].[Files]


(


    FileID uniqueidentifier NOT NULL ROWGUIDCOL PRIMARY KEY,


    FileContents varbinary(max) FILESTREAM DEFAULT(0x)


)


and the corresponding Entity Data Model and generated code look like:



public partial class Files : global::System.Data.Objects.DataClasses.EntityObject


{


    [EdmScalarProperty(EntityKeyProperty=true, IsNullable=false)]


    [DataMember]


    public global::System.Guid FileID


    {


        get { … }


        set { … }


    }


    private Guid _FileID;


    [EdmScalarProperty]


    [DataMember]


    public byte[] FileContents


    {


        get { … }


        set { … }


    }


    private byte[] _FileContents;


}


Notice that the FileContents field is defined as byte[].


Reading a File Content



FileManagementEntities ctx = new FileManagementEntities();


var query = ctx.Files;


foreach (var file in query)


{


    System.IO.File.WriteAllBytes(file.FileID + ".txt", file.FileContents);


}


In the above code block I create a new instance of the object context and query for all the files. Going over the files, I take out the file contents (as a byte array) and write it to another file in the file system.


Adding a new File



Files newFile = new Files();


newFile.FileID = Guid.NewGuid();


newFile.FileContents = System.IO.File.ReadAllBytes("TextFile1.txt");


ctx.AddObject("Files", newFile);


ctx.SaveChanges();


In the above code I create a new Files object, assign a new ID and read all the contents of a file ( as a byte array) into the FileContents property. Then, I use standard Entity Framework methods to add the file into the EntitySet and save the changes to the database.


Conclusion

ADO.Net Entity Framework adds the support of using SQL Server 2008 FILESTREAM in Visual Studio 2008 and .Net Framework 3.5 SP1. The FILESTREAM columns is represented as a byte[] field that we can access it and get the file contents.


Enjoy!

הוסף תגובה
facebook linkedin twitter email