Smoking monkey
Smoking monkey

Reputation: 323

The cast to value type 'Int64' failed because the materialized value is null

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

    }

Here is the model called 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; }
}

How should I use the DefaultIfEmpty() in this method so that I can get the values from db even if the values are null.

Upvotes: 0

Views: 3815

Answers (1)

Hamlet Hakobyan
Hamlet Hakobyan

Reputation: 33381

Use nullable Int64 instead

public Int64? Phone { get; set; }

You have redundant select in your query.

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

Upvotes: 2

Related Questions