How do I specify that a property should generate a TEXT column rather than an nvarchar(4000)

C#Entity FrameworkEf Code-FirstSql Server-CeData Annotations

C# Problem Overview


I'm working with the Code First feature of Entity Framework and I'm trying to figure out how I can specify the column data types that should be created when the database is auto-generated.

I have a simple model:

public class Article
{
    public int ArticleID { get; set; }

    public string Title { get; set; }
    public string Author { get; set; }
    public string Summary { get; set; }
    public string SummaryHtml { get; set; }
    public string Body { get; set; }
    public string BodyHtml { get; set; }
    public string Slug { get; set; }

    public DateTime Published { get; set; }
    public DateTime Updated { get; set; }

    public virtual ICollection<Comment> Comments { get; set; }
}

When I run my application, a SQL CE 4.0 database is automatically created with the following schema:

DB Schema

So far, so good! However, the data I will be inserting into the Body and BodyHtml properties is routinely larger than the maximum allowed length for the NVarChar column type, so I want EF to generate Text columns for these properties.

However, I cannot seem to find a way to do this! After quite a bit of Googling and reading, I tried to specify the column type using DataAnnotations, from information found in this answer:

using System.ComponentModel.DataAnnotations;

...

[Column(TypeName = "Text")]
public string Body { get; set; }

This throws the following exception (when the database is deleted and the app is re-run):

Schema specified is not valid. Errors: (12,6) : error 0040: The Type text is not qualified with a namespace or alias. Only PrimitiveTypes can be used without qualification.

But I have no idea what namespace or alias I should be specifying, and I couldn't find anything that would tell me.

I also tried changing the annotation as per this reference:

using System.Data.Linq.Mapping;

...

[Column(DbType = "Text")]
public string Body { get; set; }

In this case a database is created, but the Body column is still an NVarChar(4000), so it seems that annotation is ignored.

Can anyone help? This seems like it should be a fairly common requirement, yet my searching has been fruitless!

C# Solutions


Solution 1 - C#

I appreciate the effort that went into the existing answer, but I haven't found it actually answering the question... so I tested this, and found out that

[Column(TypeName = "ntext")]
public string Body { get; set; }

(the one from System.ComponentModel.DataAnnotations) will work to create an ntext type column.

(My problem with the accepted answer is that it seems to indicate that you should change the column type in the interface, but the question is how to do it programmatically.)

Solution 2 - C#

You can use the following DataAnnotation and Code-First will generate the maximum sized data type that the database allows. In the case of Sql CE it results in an underlying ntext column.

[MaxLength]

or using the EF 4.1 RC fluent API...

protected override void OnModelCreating(ModelBuilder modelBuilder){
    modelBuilder.Entity<Article>()
        .Property(p => p.Body)
        .IsMaxLength();
}

Solution 3 - C#

Have you tried ntext? I have just created a SQL CE 4.0 database, and when I manually add a column to a table, I notice that text isn't available in the list of datatypes while ntext is. Just like you can pick nvarchar but no varchar.

Unfortunately, the biggest nvarchar size you can choose is 4000. So nvarchar(max) is also not an option.

There is ntext but no text

Solution 4 - C#

The issue with using the string length attribute e.g.

[StringLength(4010)]

Is that any string > the number of chars defined in the attribute will trigger a validation exception, which kind of goes against any reason why you would use a non defined field size on a column, or you use a huge number in the attribute and lose any validation offered by the attribute. Ultimately you are using a validation mechanism to solve a mapping issue if you use the StringLength attribute, where as Marcel Popescu's answer using the Column attribute is a much better solution as it is using the mapping attributes to define type, and still allows you to use the StringLength attribute for validation.

Another option is to use the EF4 CTP5 fluent API and define the column mapping in the OnModelCreating event in the DbContext e.g.

protected override void OnModelCreating(ModelBuilder modelBuilder){
    modelBuilder.Entity<Article>()
    .Property(p => p.Body)
    .HasColumnType("nvarchar(max)");
}

Also it should be noted that NText is a deprecated data type (ntext, text, and image (Transact-SQL) MS Books Online) and the recommendation is to use NVarChar(MAX) in its place

Solution 5 - C#

I know, this is probably a year too late but:

Use:

[StringLength(-1)] 

This will create a nText field. I managed to store at least 25Kbytes in that field using the Compact Edition 4.0 database.

Solution 6 - C#

You can use System.ComponentModel.DataAnnotations.Schema.ColumnAttribute

[Column(TypeName="text")]
public string Text { get; set; }

or via Fluent API:

modelBuilder.Entity<YourEntityTypeHere>()
    .Property( e => e.Text)
    .HasColumnType("text");

Solution 7 - C#

Have you tried lowercase "text"? Per this MSDN discussion, the data provider is case sensitive.

Solution 8 - C#

This DataAnnotation will make Code-First generate a nvarchar(MAX) column in sql

[StringLength(1073741822)]

Not sure if other big numbers do the same... I got this one using the calculator and the nvarchar(MAX) spec.

I've tried it with SQL Server 2005 Express or not, but not with CE

I'm using it and it works, but I would like to know if it's a good idea or if I'm missing something... is there any other way to make code-first know that I want nvarchar(MAX)?

Solution 9 - C#

This DataAnnotation will make Code-First generate a nvarchar(MAX) column in sql also:)

[StringLength(4010)]

Solution 10 - C#

Agree that TypeName = "ntext" seems to work, although I also have to add:

[StringLength(Int32.MaxValue)]

to stop the default string length of 128 getting in the way.

Solution 11 - C#

In case you do add-migration and update-database using Package Manager, you may amend the create table by adding storeType as follows:

       CreateTable(
            "dbo.Table_Name",
            c => new
                {
                    ID = c.Int(nullable: false, identity: true),
                    Title = c.String(nullable: false, maxLength: 500),
                    Body = c.String(unicode: false, storeType: "ntext"),
                })
            .PrimaryKey(t => t.ID);

Solution 12 - C#

If you don't want to annotate all your properties and you use a contemporary EF, use a convention:

public class StringNTextConvention : Convention {
  public StringNTextConvention() {
    Properties<string>().Configure(p => p.HasColumnType("ntext"));                    
  }
}

You can call it from your onModelCreating():

modelBuilder.Conventions.Add(new StringNTextConvention());

and all your strings will automagically turn into ntext columns.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMark BellView Question on Stackoverflow
Solution 1 - C#Marcel PopescuView Answer on Stackoverflow
Solution 2 - C#MichaelView Answer on Stackoverflow
Solution 3 - C#Kristof ClaesView Answer on Stackoverflow
Solution 4 - C#nakchakView Answer on Stackoverflow
Solution 5 - C#Johan PlogfeldtView Answer on Stackoverflow
Solution 6 - C#NerdroidView Answer on Stackoverflow
Solution 7 - C#AxarydaxView Answer on Stackoverflow
Solution 8 - C#PetoView Answer on Stackoverflow
Solution 9 - C#Bohdan LyzanetsView Answer on Stackoverflow
Solution 10 - C#Steve OwenView Answer on Stackoverflow
Solution 11 - C#hsobhyView Answer on Stackoverflow
Solution 12 - C#GáborView Answer on Stackoverflow