查询中的Linq Convert.ToInt32 [英] Linq Convert.ToInt32 in Query

查看:397
本文介绍了查询中的Linq Convert.ToInt32的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些代码:

(from AspNetUsers in db.AspNetUsers
join UserDetails in db.UserDetails on new { Id = Convert.ToInt32(AspNetUsers.UserDetailId) } equals new { Id = UserDetails.Id } into UserDetails_join
where
AspNetUsers.Email == "mickeymouse@blueyonder.co.uk"
select new
{
   AspNetUsersId = AspNetUsers.AspNetUsersId,
   UsertId = (int?)UserDetails.UserID
}).ToList();

(这是包含许多联接的更大查询的摘录)

无论如何,我的问题是查询在Linger程序中可以完美运行,但是当我将查询复制到VS 2013时,由于Convert.ToInt32而失败.

Anyway, the problem I have is that the query runs perfectly within the Linger program, but when I copy the query over to VS 2013, It fails because of the Convert.ToInt32.

不知道为什么吗?

推荐答案

您不能在linq中使用Convert.ToInt32实体.

You can't use a Convert.ToInt32 in linq to entities.

一种方法是在内存中"完成所有操作(枚举全部).

One way would be to do all this "in memory" (enumerate all).

当然,这对性能确实很不利.

But of course that's really bad for performance.

根据您的情况,另一种方式是

One other way, in your case, would be

第一:在联接中执行另一种方法(将int转换为string:因为这种方法在linq中适用于实体).

First : do it the other way in the join (convert the int in a string : cause this way is doable in linq to entities).

=> new { Id = AspNetUsers.UserDetailId } equals new { Id = SqlFunctions.StringConvert((double)UserDetails.Id) }

然后:仅获取所需的数据,进行枚举并将其强制转换为对象.

Then : get only the data you need, enumerate and cast in linq to objects.

select new
{
   AspNetUsersId = AspNetUsers.AspNetUsersId,
   UsertId = UserDetails.UserID
}).ToList()
.Select (m => new {
   m => m.AspNetUsersId,
   UsertId = (int?)m.UsertId
});

最后:最好的方法是不将int存储为varchar ...

Finally : the best way would be not to store int as varchar...

这篇关于查询中的Linq Convert.ToInt32的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆