Entity Framework: The argument to DbIsNullExpression must refer to a primitive or reference type

后端 未结 2 1274
慢半拍i
慢半拍i 2021-01-16 20:07

I\'m trying to use entity to do this:

    SELECT *
    FROM aspnet_Users u LEFT JOIN (SELECT u.UserId, p.Permission, p.MediaId, p.Valid
                              


        
相关标签:
2条回答
  • I realize that since in the second query,it still have the left join with aspnet_Users table, it does not need to have u in the 1st query, so I changed it to below, it works now. But still, it will be great to know why the original code and suggested code failed.

        var up = from u in en.aspnet_Users
                         join p in en.Permissions
                             on u.UserId equals p.UserId into pu
                         from p2 in pu.DefaultIfEmpty()
                         where p2.MediaId == this.MediaId && p2.Valid == true
                         select p2;
    
                var ul = from us in en.aspnet_Users
                         join pm in up
                              on us.UserId equals pm.UserId into pm1
                         from pm2 in pm1.DefaultIfEmpty()
                         orderby us.LoweredUserName
                         select new PermissionInfo
                         {
                             Permission = (pm2 == null ? -1 : pm2.Permission1),
                             UserName = us.UserName,
                             UserId = us.UserId,
                             PermissionId = (pm2 == null ? -1 : pm2.PermissionId)
                         };
    
                ret = ul.ToList();
    
    0 讨论(0)
  • 2021-01-16 21:01

    Had a similar problem, I managed to solve it by moving the null check outside of the sql. In your case you can do it by calling ToList() before checking for Null:

    var intermediateUl = from us in en.aspnet_Users
        join pm in up
          on us.UserId equals pm.UserId into pmOuter
        from pm2 in pmOuter.DefaultIfEmpty()
        select new { us.UserName, us.UserId, pm2};
    
    var ul = intermediateUl
        .ToList()
        .Select(o => new PermissionInfo { 
            Permission = (o.pm2 == null ? -1 : pm2.Permission1), 
            PermissionId = (o.pm2 == null ? -1 : pm2.PermissionId) 
            UserName = o.UserName, 
            UserId = o.UserId, 
         });
    

    The problem surprised me as well, because couple lines above I had a similar query with outer join which passed OK. It seems that checking for null with linq outer construct is only possible with entities known by Entity Framework. Any other class, anonymous or not, confuses EF/linq.

    I know this question is old, but maybe it will help someone :)

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