2011-11-08 157 views
14

在这个查询中我有3条记录(int-(telefon = d.telefon),decimal-(pesel = d.pesel),decimal-(nip = d.nip))另一条记录是字符串。不能隐式转换类型'int?' 'int'

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

而且我有错误:

Cannot implicitly convert type 'int?' to 'int'. An explicit conversion exists (are you missing a cast?)

和两个其他错误'小数?而不是'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? 

谢谢大家的帮助,你的变量的

+0

为什么你不显示uzytkownikModel类?可能你得到的错误,因为字段或属性不符合与您的值相同的类型。 –

+0

你可以发布'd'类型的定义吗? – JohnD

+0

我增加了更多代码 – user1031034

回答

15

在你的uzytkownikModel类中,可为空的属性应该声明为“int?”或“小数?”而不是“int”和“decimal”。

26

你需要发布更多的代码来得到一个明确的答案,但一个地方是可以为空的,并且将其分配给不可为空的类型,您需要执行.Value

例如,如果你的对象D的财产imieNullable<int>,这是什么原因造成你的问题,你可以这样做:

imie = d.imie.Value 

您还需要注意的情况下,d.imie是空值。例如:

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

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

imie = d.imie ?? 0 

(我只是用d.imie为例 - 没有足够的代码发布到pintpoint确切的问题。)

+0

Dasn't与.Value一起工作...我添加了更多代码。 – user1031034

+0

d.imie.Value就像d.imie一样为我工作? 0; // 非常感谢 – Catto

3

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

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

int? w = 2; 
int? x = null; 
int y = w ?? 3; 
int z = x ?? 4; 
相关问题