【问题标题】:The cast to value type 'Int64' failed because the materialized value is null转换为值类型“Int64”失败,因为具体化值为 null
【发布时间】:2014-08-23 15:23:12
【问题描述】:
    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 中获取值。

【问题讨论】:

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


    【解决方案1】:

    改用可为空的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
                    });     
    

    【讨论】:

      猜你喜欢
      • 2013-02-24
      • 2013-06-18
      • 2015-07-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多