【问题标题】:Cannot implicitly convert type 'int?' to 'int'不能隐式转换类型“int?”到'int'
【发布时间】:2011-12-24 14:51:08
【问题描述】:

在这个查询中,我有 3 条记录 (int-(telefon = d.telefon), decimal-(pesel = d.pesel), decimal-(nip = d.nip)) 其他记录是字符串。

public ActionResult detail(int LoginID)
{
    var user = (from d in baza.uzytkowniks
                where LoginID == d.LoginID
                select new uzytkownikModel {
                    imie = d.imie, 
                    nazwisko = d.nazwisko, 
                    telefon = d.telefon, 
                    pesel = d.pesel, 
                    nip = d.nip, 
                    email = d.email, 
                    adres_zamieszkania = d.adres_zamieszkania}).ToList();

    ViewBag.daneuser = user;
    return View();
}

我有错误:

不能隐式转换类型“int?”到'int'。显式转换 存在(您是否缺少演员表?)

还有另外两个“十进制?”错误而不是'int?'。

型号:

 public class uzytkownikModel
    {
    [Required]
    public string imie { get; set; }

    [Required]
    public string nazwisko { get; set; }


    public decimal pesel { get; set; }
    public decimal nip { get; set; }

    public string adres_zamieszkania { get; set; }
    public int telefon { get; set; }
    public string email { get; set; }

}

只有 imie 和 nazwisko 是不可为空的,其余的都允许为空

//////////////////////////////////// ///////////////////////////////////////// ///////////////////////////////

现在开始工作。我改变了模型:

   decimal to decimal?

和

int to int?

谢谢大家的帮助

【问题讨论】:

  • 为什么不显示 uzytkownikModel 类?可能您收到该错误是因为字段或属性与您的值的类型不匹配。
  • 你能发布'd'类型的定义吗?

标签: linq


【解决方案1】:

您需要发布更多代码才能获得明确的答案,但是您的某个变量可以为空,并且要将其分配给您需要执行.Value 的不可为空的类型。

例如,如果您的对象 d 的属性 imie 是 Nullable<int>,这就是导致您的问题的原因,您可以这样做:

imie = d.imie.Value

您还需要注意d.imie 为空的情况。例如:

imie = d.imie.HasValue ? d.imie.Value : 0

或者,如果你喜欢 ??运算符(计算为第一个非空值):

imie = d.imie ?? 0

(我只是以d.imie 为例——没有发布足够的代码来查明确切的问题。)

【讨论】:

  • d.imie.Value 对我有用,就像 d.imie 一样?? 0; // 非常感谢
【解决方案2】:

在您的 uzytkownikModel 类中,可为空的属性应声明为“int?”或“十进制?”而不是“int”和“decimal”。

【讨论】:

    【解决方案3】:

    int? 是Nullable<int>。由于数据库列可能为 null,因此映射的属性为 Nullable。

    考虑将int? 值分配给int 变量的这段代码。

    int? w = 2;
    int? x = null;
    int y = w ?? 3;
    int z = x ?? 4;
    

    【讨论】:

      猜你喜欢
      • 2013-05-23
      • 2018-03-30
      • 1970-01-01
      • 1970-01-01
      • 2021-07-27
      • 1970-01-01
      • 1970-01-01
      • 2013-06-12
      • 1970-01-01
      相关资源
      最近更新 更多