'int'和'System.DateTime'之间没有隐式转换

时间:2017-05-22 07:13:54

标签: c#

我在映射程序的结果集时遇到错误,无法找到确切的解决方案。有人可以帮我这样做。

编码我正在使用的内容:DateOfBirth = DateOfBirth.Value == null ? 0 : Convert.ToDateTime(DateOfBirth.Value),

DateofBirth的数据类型是DateTime。

我得到的错误是“无法确定条件表达式的类型,因为'int'和'System.DateTime'之间没有隐式转换

3 个答案:

答案 0 :(得分:1)

没有从0转换为DateTime。因此无法确定?:运算符的结果类型。在一个案例中为int,在另一个案例中为DateTime。这就是编译器在错误消息中告诉你的内容。

如果您真的想要删除null条目,请使用有效的DateTime值(例如DateTime.MinValue)作为后备。

此外,您可能希望使用??运算符:

DateTime? DateOfBirth = //... can be null or not
DateTime myDateOfBirth = DateOfBirth ?? DateTime.MinValue;

当然,null可能是缺失值的更好表示......

答案 1 :(得分:0)

此代码说:

如果DateOfBirth.Value为NULL则   DateOfBirth =整数零 其他   DateOfBirth =将DateOfBirth转换为DateTime

所以,如果DateOfBirth在开头是null,那么你试图将它设置为整数零,这是不好的

答案 2 :(得分:-2)

如果您尝试比较DateTime。尝试转换成这样的东西

class AttachmentPolicy < ApplicationPolicy
  class Scope < Scope
    def resolve
      # user can see his attachments and attachments without owner
      Attachment
        .left_outer_joins(comment: [task: [:project]])
        .where('projects.user_id = ? OR comment_id IS NULL', user.id)
    end
  end

  def update?
    # if attachment doesnt have owner - anyone can change it
    record.comment.nil? ? true : owner?
  end
end

您无法将其与INT进行比较,但您可以将其与字符串

进行比较
相关问题