LINQ和可空参数

时间:2015-04-19 13:48:52

标签: c# linq nullable

我在DB中有一个可为空的字段,在模型中有可为空的参数。我尝试以下LINQ to Entities查询:

        EditPersonViewModel model = (from i in db.Person
            where i.PersonID == id.Value
            select new EditPersonViewModel()
                {
                    PersonID = i.PersonID,
                    Fullname = i.Fullname,
                    Comment = i.Comment,
                    Username = (i.UserId != null) ? i.AspNetUsers.UserName : String.Empty,
                    // this is parameter has type "int?"
                    PersonStatusID = (i.PersonStatus!=null) ? i.PersonStatus.PersonStatusID : null
                }).FirstOrDefault();

我收到编译错误:

  

错误1无法确定条件表达式的类型,因为   ' int'之间没有隐式转换。和''

它适用于

Username = (i.UserId != null) ? i.AspNetUsers.UserName : String.Empty,

但不适用于" int?"类型。为什么以及如何正确地做到这一点?

1 个答案:

答案 0 :(得分:2)

Conditional Operator的文档说: -

  

first_expression和second_expression的类型必须是   相同,或者必须存在从一种类型到另一种类型的隐式转换。

i.AspNetUsers.UserName& String.Empty string种类型适用于您。现在,你的问题是自我解释的,因为null不能被转换为整数类型,你需要这样: -

PersonStatusID = (i.PersonStatus!=null) ? i.PersonStatus.PersonStatusID : 0;

或者相反,如果你需要它作为Nullable of integer: -

PersonStatusID = (i.PersonStatus!=null) ? (int?)i.PersonStatus.PersonStatusID : null;
在这种情况下,

PersonStatusID应为int?类型。

相关问题