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

限于喜欢 提交于 2019-11-28 12:03:19

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.

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

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

Can Poyrazoğlu

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!