Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
669 views
in Technique[技术] by (71.8m points)

entity framework - EF Code First 4.1 doesn't support nvarchar(max) at all?

I've spent decent amount of time on this problem and still can't figure out why EF team makes the life so hard using Code First.

So here is some sample:

My POCO:

The way I want the thing to look like:

public class Post
{
     public int Id {get; set;}
     public string Text {get; set;}
}

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Entity<Post>()
        .Property(p => p.Text)
        .HasColumnType("nvarchar(max)");   
}

The only thing that works:

public class Post
{
     public int Id {get; set;}

     [StringLength(4000)]
     public string Text {get; set;}
}

The problem is that when in first case I try to insert anything it gives me: Validation failed for one or more entities and the second case doesn't fit my business model.

Am I the only one with this problem? How do I deal with this thing?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Using Int32.MaxValue may lead to some problems when connected to a SQL Server database. Using Int32.MaxValue in either the attribute or the api throws an exception stating "String column with MaxLength greater than 4000 is not supported". But, using either of the following methods works fine for me in EF 4.1:

You can use the MaxLengthArritbute, e.g.

[MaxLength]

public string Text { get; set; }

Or the fluent API, like so

 protected override void OnModelCreating(DbModelBuilder modelBuilder)
 {
      modelBuilder.Entity<Post>()
        .Property(s => s.Text)
        .IsMaxLength();
 }

To enforce the use of ntext use one of the following:

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

Or the fluent API, like so

 protected override void OnModelCreating(DbModelBuilder modelBuilder)
 {
      modelBuilder.Entity<Post>()
        .Property(s => s.Text)
        .HasColumnType("ntext") 
        .IsMaxLength();
 }

You may not need the MaxLength attribute in this case.

UPDATE (2017-Sep-6):

As Sebazzz pointed out in his comment ntext (and text) has been deprecated in SQL Server 2016. Here is a link to further information:

https://docs.microsoft.com/en-us/sql/database-engine/deprecated-database-engine-features-in-sql-server-2016


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...