Mark Bell
Mark Bell

Reputation: 29785

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

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!

Upvotes: 56

Views: 63608

Answers (12)

G&#225;bor
G&#225;bor

Reputation: 10274

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.

Upvotes: 1

hsobhy
hsobhy

Reputation: 1523

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);

Upvotes: 1

Johan Plogfeldt
Johan Plogfeldt

Reputation: 51

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.

Upvotes: 5

Steve Owen
Steve Owen

Reputation: 2071

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.

Upvotes: 1

Nerdroid
Nerdroid

Reputation: 13996

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");

Upvotes: 7

Michael
Michael

Reputation: 629

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();
}

Upvotes: 35

nakchak
nakchak

Reputation: 498

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

Upvotes: 6

Bohdan Lyzanets
Bohdan Lyzanets

Reputation: 1672

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

[StringLength(4010)]

Upvotes: 1

Peto
Peto

Reputation: 2690

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)?

Upvotes: 1

Marcel Popescu
Marcel Popescu

Reputation: 3351

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.)

Upvotes: 85

Kristof Claes
Kristof Claes

Reputation: 10941

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

Upvotes: 9

Axarydax
Axarydax

Reputation: 16623

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

Upvotes: 1

Related Questions