EF Code First 4.1 根本不支持 nvarchar(max)? [英] EF Code First 4.1 doesn't support nvarchar(max) at all?

查看:28
本文介绍了EF Code First 4.1 根本不支持 nvarchar(max)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经在这个问题上花费了相当多的时间,但仍然无法弄清楚为什么 EF 团队使用 Code First 让生活变得如此艰难.

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.

这里是一些示例:

我的 POCO:

我想要的样子:

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

唯一有效的方法:

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?

推荐答案

使用 Int32.MaxValue 在连接到 SQL Server 数据库时可能会导致一些问题.在属性或 api 中使用 Int32.MaxValue 会引发异常,指出不支持 MaxLength 大于 4000 的字符串列".但是,在 EF 4.1 中使用以下任一方法对我来说都很好:

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:

您可以使用MaxLengthArritbute,例如

[MaxLength]
public string Text { get; set; }

或者 fluent API,就像这样

Or the fluent API, like so

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

要强制使用 ntext,请使用以下方法之一:

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

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

或者 fluent API,就像这样

Or the fluent API, like so

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

在这种情况下,您可能不需要 MaxLength 属性.

You may not need the MaxLength attribute in this case.

更新(2017 年 9 月 6 日):

正如 Sebazzz 在他的评论中指出的那样,ntext(和 text)在 SQL Server 2016 中已被弃用.以下是更多信息的链接:

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

这篇关于EF Code First 4.1 根本不支持 nvarchar(max)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆