代码之家  ›  专栏  ›  技术社区  ›  Ted

将字符串设置为“varchar”而不是“nvarchar”的SQL类型

  •  12
  • Ted  · 技术社区  · 14 年前

    我有以下映射:

    public class LogEntryMap
    {
        public LogEntryMap()
        {
            Map.Id(x => x.Id).GeneratedBy.Identity();
            Map(x => x.Context).CustomSqlType("varchar").Length(512);
        }
    }
    

    但是,使用 SchemaExport 若要在SQL Server 2008中生成数据库,生成的脚本将忽略长度,因此实际上它是 varchar 长度为1:

    create table OV_SAC.dbo.[LogEntry] (
        Id BIGINT IDENTITY NOT NULL,
       Context varchar null,
       primary key (Id)
    )
    

    .CustomSqlType("varchar 512") 引发异常。而且没有定义 CustomSqlType ,字符串映射到 nvarchar (这确实尊重 Length 属性)。

    有什么建议吗?

    4 回复  |  直到 8 年前
        1
  •  23
  •   BartoszKP JuanBoca    8 年前

    使用 .CustomType("AnsiString") 而不是违约 "String" NHibernate将使用 varchar 而不是 nvarchar .

        2
  •  16
  •   Jonathan Moffatt    13 年前

    如果你想的话 全部的 对于要映射到varchar而不是nvarchar的字符串,可以考虑使用约定:

    /// <summary>
    /// Ensures that all of our strings are stored as varchar instead of nvarchar.
    /// </summary>
    public class OurStringPropertyConvention : IPropertyConvention
    {
        public void Apply(IPropertyInstance instance)
        {
            if (instance.Property.PropertyType == typeof (string))
                instance.CustomType("AnsiString");
        }
    }
    

    然后映射可以返回到一个简单的映射:

    Map(x => x.Context);
    

    确保你记得告诉Fluent NH使用惯例:

            var configuration = new Configuration();
            configuration.Configure();
            Fluently
                .Configure(configuration)
                .Mappings(m => m.FluentMappings
                    .AddFromAssemblyOf<Widget>()
                    .Conventions.Add<OurStringPropertyConvention>()
                    )
                .BuildSessionFactory();
    
        3
  •  8
  •   Ted    14 年前

    多哈。

    Map(x => x.Context).CustomSqlType("varchar (512)");
    
    create table OV_SAC.dbo.[LogEntry] (
        Id BIGINT IDENTITY NOT NULL,
       Context varchar (512) null,
       primary key (Id)
    )
    
        4
  •  0
  •   Joel WZ    9 年前

    我们发现使用“customtype”(“ansistring”)选项确实会阻止它使用nvarchar,但是它为指定为varchar(30)的列设置了8000的字段长度。8000 varchar比4000 nvarchar快得多,但它仍然导致了SQL Server开销方面的巨大问题。