简体   繁体   中英

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'

List<tblX> messages = (from x in db.tblX where x.msg_id == id_id 
                           || x.name == firstName  select x).ToList();

I get the error:

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'.

I have a property msg_blocked in db, which is nullable and integer. I know that I need to make a conversion, but I don't use it or need it anywhere in my linq.

Seems like your class definition for tblX doesn't match the database representation, so either modify your class to accept a nullable value, or just project out the required fields:

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();

Addendum: The reason you run into this problem is behind the scenes when you select x this is translated into a select new tblX which projects into all its available fields. The code provided is more explicit and specifies which fields to query for and then project into.

List<tblX> messages = (from x in db.tblX 
                       where (x.msg_id == id_id || x.name == firstName) && 
                              x.msg_blocked != null
                       select x).ToList();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM