Fluent NHibernate使用nvarchar(max)自动化字符串列表

时间:2011-10-14 17:39:55

标签: c# nhibernate fluent-nhibernate

我正在使用Fluent NHibernate 1.2 for NHibernate 3.1。我有一节课:

public class Marks
{
    public virtual int Id { get; set; }
    public virtual IList<string> Answers { get; set; }
}

在Marks类的映射中,我有:

HasMany(m => m.Answers).Element("Value");

创建表格后,将使用以下列创建“Answers”表:

Marks_id (FK, int, not null)
Value (nvarchar(255), null)

我想要做的是将值设为nvarchar(max)。我宁愿不为每个班级的每个字符串做这个,只为这一个班级。

我查看过这些帖子:firstsecondthird,但还没有找到任何有用的内容。

提前感谢您提供的任何帮助。如果您需要其他信息,请告诉我们。

修改 这是解决问题的代码:

HasMany(x => x.Answers).Element("Value", x => x.Columns.Single().Length = 4001);

3 个答案:

答案 0 :(得分:3)

您可以使用string强制映射CustomSqlType("nvarchar(max)")到每个列级别的更长列,或者更普遍地通过设置Length(4001)(SQL Server幻数,高于此值)它会自动创建nvarchar(max)

要自动将其应用于实体中的所有string列,您可以编写自己的FluentNHibernate convention

public class LongStringConvention : IPropertyConvention, IPropertyConventionAcceptance
{
    public void Accept(IAcceptanceCriteria<IPropertyInspector> criteria)
    {
        criteria.Expect(x => x.Type == typeof(string));
    }

    public void Apply(IPropertyInstance instance)
    {
        instance.Length(4001);
    }
}

并将其注册在映射容器中,即:

Fluently.Configure()
    .Mappings(...)
    .Conventions.Add<LongStringConvention>()

要将其应用于字符串集合,您可以使用自定义元素映射:

HasMany(x => x.Answers).Element("Value", x => x.Columns.Single().Length = 4001);

答案 1 :(得分:0)

我自己遇到过这个问题,上面的答案对我指向正确的方向非常有帮助......但我使用的是更新版本的FluentNH。

对于Fluent NHibernate 1.3和NH 3.3.1,正确的代码是:

HasMany(x => x.Answers).Element("Value", x => x.Length(4001));

答案 2 :(得分:0)

以上答案仅适用于旧版本的nhibernate。 如果您尝试HasMany(x => x.Answers).Element("Value", x => x.Length(4001));,您将获得以下内容:

  

错误属性或索引器   'FluentNHibernate.MappingModel.ColumnMapping.Length'不可能   分配给 - 它是只读的

正确现在这样做的方法是(NHibernate 4.0.2.4,FluentNHibernate 2.0.1.0):

HasMany(m => m.Answers).Element("Value", e => e.Length(4001))
相关问题