转换为值类型“Int64”失败,因为具体化值为null

时间:2014-08-23 07:16:21

标签: c# linq asp.net-mvc-4 linq-to-sql

    public ActionResult Index()
    {
        int id = WebSecurity.CurrentUserId;
        //return RedirectToAction("Details", "Profile", new  {id = WebSecurity.CurrentUserId });
        var test = (from u in db.Users
                    where u.Id == id
                    select new { u.Id, u.Name, u.Email, u.CompanyName, u.Phone, u.Address, u.Profession })
                     .Select(m => new UserIndex
                {
                    Id = m.Id,
                    Name = m.Name,
                    Email = m.Email,
                    CompanyName = m.CompanyName,
                    Phone =  m.Phone,
                    Address = m.Address,
                    Profession = m.Profession
                }).AsEnumerable();         

        return View(test);

    }

这是名为UserIndex的模型

 public class UserIndex
{
    [Key]
    public int Id { get; set; }
    public string Name { get; set; }       
    public string Email { get; set; }
    public string CompanyName { get; set; }
    public Int64 Phone { get; set; }
    public string Address { get; set; }
    public string Profession { get; set; }
    public bool Status { get; set; }
}

我应该如何在此方法中使用DefaultIfEmpty(),这样即使值为null,我也可以从db获取值。

1 个答案:

答案 0 :(得分:2)

使用可空Int64代替

public Int64? Phone { get; set; }

您的查询中有冗余选择。

var test = (from u in db.Users
                where u.Id == id
                select new UserIndex
                {
                    Id = u.Id,
                    Name = u.Name,
                    Email = u.Email,
                    CompanyName = u.CompanyName,
                    Phone =  u.Phone,
                    Address = u.Address,
                    Profession = u.Profession
                });