3

I want to save PDF files in mssql using nhibernate. How do i go about it.

I read little bit about it here, it tells that you can create a type to save the file as :

Map(x => x.Bytes)
  .CustomSqlType("VARBINARY (MAX) FILESTREAM")
  .Length(2147483647)

but I am still not able to understand what should be c# type of the field & and if its not FileInfo/FileStream then how to read write to that field.

Community
  • 1
  • 1
harishr
  • 17,807
  • 9
  • 78
  • 125

1 Answers1

4

DB type Varbinary, has its C# representation byte[]

public virtual MyFile byte[] { get; set; }

Based on app type (e.g. web with ASP.NET Web API) we can provide "download" functionality like

protected virtual HttpResponseMessage Download(string fileName, string contentType
    , byte[] data)
{
    var path = fileName;
    var result = new HttpResponseMessage(HttpStatusCode.OK);
    var stream = new MemoryStream(data);
    result.Content = new StreamContent(stream);
    result.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType);
    result.Content.Headers.Add("Content-Disposition", "attachment; fileName=" + path);

    return result;
}
Radim Köhler
  • 122,561
  • 47
  • 239
  • 335
  • Well... answer is you can. But I would say why.. `byte[]` is really good enough for us. Because we can serialize it for any purposes *later*. I mean, if you really want to do some trick, do it like: 1) map **protected** `byte[]` property 2) create **public** property consuming that field and presenting it as ... filestream. Example of the techinque: http://stackoverflow.com/a/24052062/1679310 – Radim Köhler Nov 01 '14 at 05:19
  • so you mean using get/set we should create/return fileInfo? – harishr Nov 01 '14 at 05:22
  • If you really need.. I would go this way. But my approach is: keep it `byte[]` as long as possible. Only *(finally)* on the service API (web api, asp.net mvc, routine...) just there convert it... Does it help? – Radim Köhler Nov 01 '14 at 05:23
  • Good luck with NHibernate sir, it is amazing tool ;) – Radim Köhler Nov 01 '14 at 05:24
  • @radim-kolher can you please have a look at [this question](http://stackoverflow.com/questions/26686494/nhibernate-read-write-list-of-string) whenever you have time... – harishr Nov 01 '14 at 06:08
  • I saw this question, but did not have enough courage to tell you: I would not go this way... Why? I will give a comment there – Radim Köhler Nov 01 '14 at 06:28
  • @radhim-kohler i m still waiting :) – harishr Nov 01 '14 at 14:20
  • @harish, I gave you my view in a comment below of your [question](http://stackoverflow.com/q/26686494/1679310) – Radim Köhler Nov 01 '14 at 14:53