【问题标题】:The null value cannot be assigned to a member with type System.Boolean which is a non-nullable value type不能将 null 值分配给 System.Boolean 类型的成员,该类型是不可为 null 的值类型
【发布时间】:2014-01-22 10:11:17
【问题描述】:
select new
{
    countFair = (pstvte.Fair),
});

我已将 Fair 列的默认值设置为“false”。现在我在新字段中分配这个不可为空的布尔值时,它给出了以下错误:

null 值不能分配给 System.Boolean 类型的成员,该类型是不可为 null 的值类型

CREATE TABLE [dbo].[PostVote](
    [PostVoteId] [bigint] IDENTITY(1,1) NOT NULL,
    [PostId] [bigint] NOT NULL,
    [UserId] [bigint] NOT NULL,
    [Fair] [bit] NOT NULL,
    [NotFair] [bit] NOT NULL,
 CONSTRAINT [PK_PostVote] PRIMARY KEY CLUSTERED 
(
    [PostVoteId] 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

ALTER TABLE [dbo].[PostVote] ADD  DEFAULT ('False') FOR [Fair]
GO

ALTER TABLE [dbo].[PostVote] ADD  DEFAULT ('False') FOR [NotFair]
GO

【问题讨论】:

  • 你确定 pstvte 不为空吗?
  • 它永远不能为空,因为我已经将它的默认值定义为“False”
  • 你能告诉我们countFair和FAIR的定义吗?
  • 听起来数据库中可能有一个空值。你能确认是不是这样吗?
  • 这些是数据库定义。生成的实际代码呢?

标签: c# linq nullable


【解决方案1】:

我认为您需要更改countFair的声明

来自

bool countFair;

bool? countFair;

或者

做这样的事情

select new
{
    countFair = (pstvte.Fair.HasValue ? pstvte.Fair.Value : false ),
});

【讨论】:

  • countFair = pstvte.Fair ?? false,
猜你喜欢
  • 2013-04-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-11-28
相关资源
最近更新 更多