Linq Convert.ToInt32 in Query

后端 未结 2 1943
天命终不由人
天命终不由人 2021-01-22 04:34

I have some code:

(from AspNetUsers in db.AspNetUsers
join UserDetails in db.UserDetails on new { Id = Convert.ToInt32(AspNetUsers.UserDetailId) } equals new { I         


        
相关标签:
2条回答
  • 2021-01-22 04:51

    You can use cast (i.e (int?)AspNetUsers.UserDetailId) instead of Convert and EF providers should implement it (is related to the provider). SQL Server EF provider probably converts it to CAST AS

    0 讨论(0)
  • 2021-01-22 05:03

    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

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

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

    0 讨论(0)
提交回复
热议问题