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

浪子不回头ぞ 提交于 2019-11-28 06:52:18

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

Use this:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    base.OnModelCreating(modelBuilder);

    modelBuilder.Entity<Post>()
        .Property(p => p.Text)
        .HasMaxLength(Int32.MaxValue);
}

Or this:

[StringLength(Int32.MaxValue)]
public string Text { get; set; }

Using the [MaxLength] attribute without any value, as described in Andre Artus's post, works perfectly. Under SQL CE it correctly uses "ntext", while under SQL Server it uses "nvarchar(max)". This is highly desired, but should be made clearer in the documentation.

I used the code below to get nvarchar(max) for a field in database. I am using EF5.

using System.Data.Entity.ModelConfiguration;
using Lansw.Panels.Domain.Entities;

    namespace Lansw.Panels.DataAccess.Configurations
    {
        internal class ServiceAgreementConfiguration : EntityTypeConfiguration<ServiceAgreement>
        {
            public ServiceAgreementConfiguration()
            {
                Property(t => t.ServiceAgreementText).IsRequired().IsMaxLength();
            }
        }
    }

I resolved my problem with something like this:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    base.OnModelCreating(modelBuilder);

    modelBuilder.Entity<Post>()
        .Property(p => p.Text)
        .IsMaxLength()
        .HasColumnType("nvarchar(max)");
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!