【问题标题】:The property 'x' on 'tblX' could not be set to a 'null' value. You must set this property to a non-null value of type 'Int16''tblX' 上的属性 'x' 无法设置为 'null' 值。您必须将此属性设置为“Int16”类型的非空值
【发布时间】:2012-11-02 16:25:48
【问题描述】:
List<tblX> messages = (from x in db.tblX where x.msg_id == id_id
|| x.name == firstName select x).ToList();
我得到错误:
“tblX”上的属性“x”无法设置为“null”值。您必须将此属性设置为“Int16”类型的非空值。
我在 db 中有一个属性 msg_blocked,它可以为空且为整数。我知道我需要进行转换,但我不使用它或在我的 linq 中的任何地方都不需要它。
【问题讨论】:
标签:
c#
database
linq
entity-framework
types
【解决方案1】:
似乎您的 tblX 类定义与数据库表示不匹配,因此要么修改您的类以接受可为空的值,要么只投影出所需的字段:
List<tblX> messages = (from x in db.tblX
where (x.msg_id == id_id || x.name == firstName)
select new tblX
{
//required fields
msg_id = x.msg_id,
name = x.name,
...
}).ToList();
附录:你遇到这个问题的原因是你在幕后
select x
这被翻译成
select new tblX
它投射到所有可用的领域。提供的代码更加明确,并指定了要查询然后投影到的字段。
【解决方案2】:
List<tblX> messages = (from x in db.tblX
where (x.msg_id == id_id || x.name == firstName) &&
x.msg_blocked != null
select x).ToList();