简体   繁体   中英

C# Entity Framework - Long String not being persisted as NVARCHAR(MAX)

I am very new to C# and I'm developing a small application to test the code-first approach on Entity Framework.

My application has a class Download which contains the following properties:

[Key]
public int DownloadId { get; set; }
public string URL { get; set; }
public Boolean IsFinished { get; set; }
[Column(TypeName = "nvarchar(MAX)")]
public string Contents { get; set; }

In my Main method I create some HTTP GET requests to several web pages and insert their response into the Contents column using a DbContext:

//Persist the download first without contents, just the URL
context.Downloads.Add(d);
context.SaveChanges();


// Create request
request = WebRequest.Create(d.URL);
request.Method = "GET";

response = request.GetResponse();
dataStream = response.GetResponseStream();
reader = new StreamReader(dataStream);

responseFromServer = reader.ReadToEnd();

reader.Close();
dataStream.Close();
response.Close();

d.Contents = responseFromServer;
Console.WriteLine("d.Contents= " + d.Contents);
context.SaveChanges();

It works perfectly for most pages. Whenever the page is a bit bigger ,though (which means a longer string), the Contents are empty.

I tested the contents of the string (see one line before last, above) and I got the complete contents of the web page, which means the problem is exactly on the last line (contexto.SaveChanges()). In other words, a have a relatively large string which should be persisted to an NVARCHAR(MAX) column and for some reason it is not being persisted.

Any ideas?

I found out what was wrong. The Server Explorer in Visual Studio doesn't show the contentes of the NVARCHAR(MAX) column if it's longer than 43679 bytes, even if the data is there.

Also, the download happened within a thread context; when the page was big I was querying the database before the download had finished and thus got an empty reply.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM