编程语言
首页 > 编程语言> > c# – 可空属性的映射结果为0但不是Null

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

作者:互联网

我通过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.

那么我在这里做错了什么?

使用NHibernate 3.1和FluentNHibernate 1.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);)

标签:c,sql-server,nhibernate,nullable,fluent-nhibernate
来源: https://codeday.me/bug/20190702/1360490.html