Unable to create a constant value of type (type) Only primitive types ('such as Int32, String, and Guid') are supported in this context

前端 未结 4 616
离开以前
离开以前 2020-12-11 02:29

I\'ve read ALL of:

  • Unable to create a constant value of type 'System.Object' in Entity Framework

  • Entity Framework - "Unable to

相关标签:
4条回答
  • 2020-12-11 03:08

    I ran into a similar problem, and instead of IQueryable, I tried using List, and it worked. May be of some help.

    0 讨论(0)
  • 2020-12-11 03:21

    It will not work because you want to use local Album in linq-to-entities query. You must either use navigation property on p to get its album:

    var query = from p in VisibleObjects.OfType<Photo>()
                where p.Album.Id == alb.Id
                select p;
    

    or you must build complex query with some join between photos and albums. You cannot pass local object and any its relation to the query. Only simple properties can be passed.

    0 讨论(0)
  • 2020-12-11 03:23

    I think that EF is trying to convert where a.Photos.Contains(p) into SQL like WHERE p IN (a.Photos), but it doesn't know how to express a.Photos in SQL. The SQL you want probably looks like WHERE p.Id IN (1, 2, 3), so you could try doing that in C#:

    static IQueryable<Photo> VisiblePhotos(this Album a)
    {
        var photoIds = a.Photos.Select(p => p.Id).ToArray();
        return from p in VisibleObjects.OfType<Photo>() where photoIds.Contains(p.Id) select p;
    }
    
    0 讨论(0)
  • 2020-12-11 03:26

    I tried another way around and it worked:

    static IQueryable<Photo> VisiblePhotos(this Album a)
    {
        return from p in VisibleObjects.OfType<Photo>()
               where p.Albums.Any(alb => a.ID == alb.ID)
               select p;
    }
    

    Quite weird to see this works but the other one not. But I'm still wondering why Contains is not working.

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