simon.d
simon.d

Reputation: 2531

Save a long string in SQL database using Entity Framework

I'm trying to save the contents of a website to my database using Entity Framework. However, when the length of the HTML > 4000, I get these validation errors:

A first chance exception of type 'System.Data.Entity.Validation.DbEntityValidationException' occurred in EntityFramework.DLL WebDev.WebServer40.exe Information: 0 : Property: RawData Error: The field RawData must be a string or array type with a maximum length of '4000'.

Any idea how to get around this? RawData is being created as NVARCHAR(4000) but a better type would be TEXT. Can I force that somehow?

Thanks!

Upvotes: 5

Views: 14304

Answers (5)

Amir Hajiha
Amir Hajiha

Reputation: 935

I [almost] used Kyle Nunery's answer except that as I needed it for MySql and large strings to be stored, I thought it would be useful to know what else you can use instead of the "text" type.

The maximum amount of data that can be stored in each data type is as follows:

TINYTEXT 256 bytes

TEXT 65,535 bytes ~64kb

MEDIUMTEXT 16,777,215 bytes ~16MB

LONGTEXT 4,294,967,295 bytes ~4GB

Upvotes: 0

Savvas Sopiadis
Savvas Sopiadis

Reputation: 8223

I'm using SQL CE 4.0 and having the very same problem. I managed to solve it using the following DataAnnotation (i like annotations :) )

public class Page
    {
        [Key]
        public int PageId { get; set; }

        [MaxLength]
        public string Content { get; set; }
    }

Now i can save whatever content in the Content property!

Upvotes: 8

Adam Wenger
Adam Wenger

Reputation: 17570

The TEXT data type has been deprecated in favor of NVARCHAR(MAX), I would use that to save yourself refactoring down the road.

http://technet.microsoft.com/en-us/library/bb510662.aspx

SQL CE doesn't support NVARCHAR(MAX) so it limits your strings to NVARCHAR(4000)

If it is possible to use SQL Server 2008, Entity Framework will generate NVARCHAR(MAX) columns for you from your strings.

Upvotes: 3

Kyle Nunery
Kyle Nunery

Reputation: 2049

Are you using EF Code First? You can designate the text type in an entity mapping file.

Example mapping file:

public class CustomerMap : EntityTypeConfiguration<Customer>
{
    this.Property(t => t.Description).HasColumnType("text");
}

Then you have to register your mapping file in your dbContext class in the OnModelCreating method:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
     modelBuilder.Configurations.Add(new CustomerMap());
     base.OnModelCreating(modelBuilder);
}

Upvotes: 0

Jonats
Jonats

Reputation: 401

TEXT type would be a better option. However this is memory hungry compared to a limited nvarchar.

Alternatively you can use BLOB but will require you to do some string data processing.

Upvotes: 2

Related Questions