ASP.NET Linq查询

3
System.Linq.IQueryable<CustomerProfile> query = 
    from usr in context.customer_profiles
    where usr.cust_email == LoginID
    select new CustomerProfile
    {
        NAME = usr.cust_name,
        CONTACT = usr.cust_contact,
        EMAILID = usr.cust_email,
        LOCATION = usr.cust_location,
        SERVICELOCATION=usr.cust_service_location,
        FAXNO=usr.cust_fax_no,
        FIRMNAME = usr.cust_firm_name,
        FIRMADDRESS = usr.cust_firm_address,
        DATEESTABLISHED = Convert.ToDateTime(((DateTime?)usr.date_of_established)),
        SIGNATURE = usr.cust_signature,
        LOGO =  usr.logo,
    };

在下面这行代码中,我遇到了“指定的强制转换无效”的问题。我该如何纠正它?

return query.ToList().FirstOrDefault(); 

2
你能告诉我异常的详细信息吗,比如内部异常或堆栈跟踪? - Jeffrey Zhao
usr.date_of_established 的类型是什么?无论如何,显式转换后跟 Convert 是多余的。此外:您通过此查询从数据库中获取了 所有 customer_profiles。ToList() 不是必需的。我敢打赌异常与日期时间有关。如果省略该行,它是否仍然发生? - Gert Arnold
2
另一个问题:所有这些代码所在的方法签名是什么?它是否期望返回其他内容? - Gert Arnold
2个回答

0

你正在将客户的电子邮件与他们的登录ID在查询中进行比较。我认为这可能会导致一个转换问题,如果不是的话,它可能不会返回你想要的正确结果。

并且使用隐式转换(var)而不是IQueryable。


1
这会导致编译器错误,如“无法将'=='运算符应用于类型为'string'和'int'的操作数”。 - Gert Arnold

0
尝试这个,然后返回查询。对于格式问题感到抱歉,它让我感到头疼。
        CustomerProfile query =
         (from usr in context.customer_profiles
          where usr.cust_email == LoginID
          select new
          {
              NAME = usr.cust_name,
              CONTACT = usr.cust_contact,
              EMAILID = usr.cust_email,
              LOCATION = usr.cust_location,
              SERVICELOCATION = usr.cust_service_location,
              FAXNO = usr.cust_fax_no,
              FIRMNAME = usr.cust_firm_name,
              FIRMADDRESS = usr.cust_firm_address,
              DATEESTABLISHED = Convert.ToDateTime(((DateTime?)usr.date_of_established)),
              SIGNATURE = usr.cust_signature,
              LOGO = usr.logo,
          }).FirstOrDefault();

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接