Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 669
Mark Bell Avatar asked Feb 04 '11 07:02

Mark Bell


1 Answers

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

like image 119
Marcel Popescu Avatar answered Sep 21 '22 03:09

Marcel Popescu