JTew
JTew

Reputation: 3189

Is there a way to override the nvarchar(max) with a set maxlength value using EF 4.2 codefirst configuration?

By default EF 4.2 codefirst sets the database column behind string properties to nvarchar(max).

Individually (per property) I can override this convention by specifying the [MaxLength(512)] attribute.

Is there a way of globally applying a configuration that does this? It seems that the configuration api on modelbuilder only allows for per entity overrides and that the convention api on modelbuilder only allows removes. See this question.

Upvotes: 4

Views: 2448

Answers (2)

Pankaj Upadhyay
Pankaj Upadhyay

Reputation: 13594

I think you can do that. Just above your property in the model table add the StringLength Attribute. Just like following. (Remember you will need to include using System.ComponentModel.DataAnnotations;)

    [StringLength(160)]
    public string Title { get; set; }

Update

  • First of all, You cannot create an index on an nvarchar(MAX) column. You can use full-text indexing, but you cannot create an index on the column to improve query performance.

  • From the storage prospective there are no difference between nvarchar(max) and nvarchar(N) when N < 4000. Data is stored in row or on the Row-overflow pages when does not fit. When you use nvarchar(max) and stores more than 4000 characters (8000 bytes) SQL Server uses different method to store the data - similar to old TEXT data type - it stores in the LOB pages.

  • Performance-wise - again, for N<4000 and (max) - there is no difference. Well, technically it affects row size estimation and could introduce some issues - you can read more about it here: Optimal way for vaiable width colums

  • What can affect the performance of the system is the row size. If you have queries that SCAN table, large row size will lead to more data pages per table -> more io operations -> performance degradation. If this is the case, you can try to do the vertical partitioning and move nvarchar field to the different table.

Upvotes: 2

Ladislav Mrnka
Ladislav Mrnka

Reputation: 364409

No there is no global configuration available. Custom conventions were removed from EF Code First in CTP phase.

Upvotes: 3

Related Questions