[英]Assigning null value to nullable boolean in struct init
I've scoured stack overflow for the answer to my problem but nothing matches my situation. 我一直在寻找堆栈溢出的问题的答案,但是没有任何一种情况适合我。
I've got a struct which represents the schema of data retrieved from a stored procedure. 我有一个结构,它表示从存储过程检索的数据的架构。 the data type for a boolean field is nullable, but when the value returned is null, I cannot assign the value to the list item.
布尔字段的数据类型可以为空,但是当返回的值为空时,我无法将值分配给列表项。
Struct looks like this: 结构看起来像这样:
public GuidelineSchema gl;
public struct GuidelineSchema
{
public int id;
public int GLtypeID;
public int typeValue;
public Nullable<bool> isInlineLayout;
public int ResinGroupID;
public int NotResinGroupID;
public int ResinSubTypeID;
.
.
.
}
and I populate it here 我在这里填充
using (SqlDataReader sdr = cmd.ExecuteReader())
{
while (sdr.Read())
{
GuidelineSchema gl = new GuidelineSchema() {
id = sdr.IsDBNull(0) ? 0 : sdr.GetInt32(0),
GLtypeID = sdr.IsDBNull(1) ? 0 :sdr.GetInt32(1),
typeValue = sdr.IsDBNull(2) ? 0 : sdr.GetInt32(2),
//isInlineLayout = sdr.IsDBNull(3) ? (bool?)null : sdr.GetBoolean(3),
//isInlineLayout = (bool?)sdr.GetSqlBoolean(3),//.GetBoolean(3),
//isInlineLayout = (Nullable<Boolean>)sdr.GetBoolean(3),// sdr.IsDBNull(3) ? : sdr.GetBoolean(3),//sdr.IsDBNull(3) ? false :
//isInlineLayout = sdr.IsDBNull(3) ? (bool?)null : sdr.GetSqlBoolean(3),
isInlineLayout = sdr.GetBoolean(3),
ResinGroupID = sdr.IsDBNull(4) ? 0 : sdr.GetInt32(4),
NotResinGroupID = sdr.IsDBNull(5) ? 0 : sdr.GetInt32(5),
.
.
.
The problem occurs only when the db value is null. 仅当db值为null时,才会出现此问题。 I've tried all the different checks, and casts, each time I get the error.
每次收到错误时,我都会尝试所有不同的检查和强制转换。 I've read up on sql data types, nullable data types.
我已经阅读了sql数据类型,可为空的数据类型。 It works if i set the value to true or false if it's null, but I actually need it to be null if it's null.
如果我将值设置为true或false(如果为null),则可以使用,但是如果为null,则实际上我需要将其设置为null。
Anyone know how I can get this done and allow the value to be null when it is supposed to be? 任何人都知道如何完成此工作并允许该值在应为null时为空?
Try 尝试
isInlineLayout = sdr[3] as bool?
we can take advantage of the fact that the data reader will return DbNull.Value if the column value is null. 我们可以利用以下事实:如果列值为null,则数据读取器将返回DbNull.Value。 The as operator will produce a null if the value cannot be cast to bool?, which DbNull cannot.
如果不能将值强制转换为bool ?,则as运算符将产生null,而DbNull则不能。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.