可空属性的映射结果为0但不是Null

时间:2015-04-23 20:25:51

标签: c# sql-server nhibernate fluent-nhibernate nullable

我通过FluentMapping定义了以下映射

public class RuleMap : ClassMap<Rule>
{
    public RuleMap()
    {
        Table("NEW");

        Id(x => x.Id, "Id").Not.Nullable();
        Map(x => x.SenderId, "SenderId").Nullable();
    }
}

以下课程

public class Rule
{
    public virtual int Id { get; set; }

    public virtual int? SenderId { get; set; }
}

我在数据库中的表定义为

USE [Test]
GO

/****** Object:  Table [dbo].[NEW]    Script Date: 23.04.2015 22:14:53 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE TABLE [dbo].[NEW](
    [Id] [int] NOT NULL,
    [SenderId] [int] NULL,
 CONSTRAINT [PK_NEW] PRIMARY KEY CLUSTERED 
(
    [Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO

并且只有一个条目

Id  | SenderId
 1  |  `NULL`

现在我通过SessionFactory加载所有规则

var rules = sessionFactory.QueryOvery<Rule>.List();

该列表包含1个项目(到目前为止一直很好),但属性SenderId的值 0 非NULL 是我所期望的。< / p>

那我在这里做错了什么?

使用NHibernate 3.1和FluentNHibernate 1.2。

1 个答案:

答案 0 :(得分:2)

将地图更改为,

public class NullableMap : ClassMap<Nullable>
{
    public NullableMap()
    {
        Table("nullable");
        LazyLoad();
        Id(x => x.Id).GeneratedBy.Identity().Column("id");
        Map(x => x.SenderId, "SenderId").Nullable().Default(null);
    }
}

其中默认值设置为null(.Default(null);