ASP.net MVC CheckBoxFor铸造错误 [英] ASP.net MVC CheckBoxFor casting error

查看:362
本文介绍了ASP.net MVC CheckBoxFor铸造错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个连接到包含名为活动位字段一个SQL表EF实体。我生成从T4模板编辑code和页面从EF实体继承。在页面的底部,它产生了CheckBoxFor是这样的:

I have a EF entity that is tied to a SQL table that contains a bit field called "Active". I generate the Edit code from the T4 template, and the page inherits from the EF entity. At the bottom of the page, it generated a CheckBoxFor like this:

<%= Html.CheckBoxFor(model => model.Active) %>

我得到了美妙的红色波浪model.Active之下,该错误信息说我不能隐式转换bool类型?为bool。于是,我尝试了以下内容:

I get the wonderful red squiggly under model.Active, and the error message says that I cannot implicitly convert type bool? to bool. So, I tried the following:

<%= Html.CheckBoxFor(model => (bool)model.Active) %>

这当然不喜欢这一点,给了我这个错误:

It, of course, didn't like that and gave me this error:

System.InvalidOperationException:
  模板可以只用现场使用
  访问属性访问,
  一维数组索引,或者
  单参数自定义索引
  前pressions。

System.InvalidOperationException: Templates can be used only with field access, property access, single-dimension array index, or single-parameter custom indexer expressions.

我可能失去了一些东西简单。

I'm probably missing something simple.

推荐答案

尝试 model.Active.Value

如果该字段应不为空的话,你应该改变数据库端的数据类型为不为空

If this field should be not nullable then you should change data type on database side to not null.

修改

为什么会出现这种情况?

Why does this happen?

您的数据库字段定义为 FIELDNAME BIT NULL 。这意味着它可以包含三个值:NULL,真假。因为它可以包含三个值,它被映射为bool?键入实体框架。布尔?为可空和的另一个名称;布尔&GT; ,这大约是布尔封装允许它具有第三个值:NULL。由于CheckBoxFor需要两个值中的一个 - 真的还是假的,它不能只是可空&LT;布尔&GT; 。每个可空有财产所谓价值返回包装类型。但你应该知道,当数据库字段将包含null 可空&LT;布尔&GT; .value的将抛出一个错误。如果你确信这个领域不应该包含NULL值,你应该改变它的数据类型为 FIELDNAME BIT NOT NULL ,再次生成数据库模型。这将从布尔改变数据类型?为BOOL而且将非常具有无需调用Value属性。

Your database field is defined as FIELDNAME BIT NULL. It means that it can contain three values: NULL, true and false. Since it can contain three values, it is mapped to bool? type in entity framework. bool? is another name of Nullable<bool>, which is wrapper around bool allowing it to have third value: NULL. Since CheckBoxFor expects one of two values - true or false, it can't except Nullable<bool>. Every Nullable has property called value which returns wrapped type. But you should be aware that when database field will contain null Nullable<bool>.Value will throw an error. If you are sure that this field should not contain NULL values, you should change it's data type to FIELDNAME BIT NOT NULL and generate model from database again. This will change data type from bool? to bool and there willbe no need to call Value property.

这篇关于ASP.net MVC CheckBoxFor铸造错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆